2012-01-17 32 views
0

我有一個類:人如何改變Java列表對象的特定字段jsonarray

class Person{ 
    String name; 
    String age; 
} 

我想翻譯人員名單jsonArray,但只有名稱字段中的結果。但是,如果我使用

List<Person> persons = new ArrayList<Person>(); 
persons.add(new Person("Jack","12")); 
JSONArray result = JSONArray.fromObject(persons); 

結果將包括年齡字段。

我該怎麼辦?

+0

你如何轉換的人只包括年齡 – Farmor 2012-01-17 09:56:34

回答

1

我的解決辦法是UTIL功能createJsonObjects,使用:

JSONArray result = createJsonObjects(persons, "name", "name") 

import org.springframework.beans.BeanUtils; 
import org.springframework.util.Assert; 
import org.springframework.util.ReflectionUtils; 
import org.springframework.util.StringUtils; 

public static JSONArray createJsonObjects(List<?> objs, String propertyNames, String jsonKeys) 
{ 
    Assert.hasText(propertyNames); 
    Assert.notNull(objs); 

    JSONArray result = new JSONArray(); 
    String[] propertyNameArray = propertyNames.split(";"); 
    String[] jsonKeysArray = propertyNameArray; 
    if (StringUtils.hasText(jsonKeys)) 
    { 
     jsonKeysArray = jsonKeys.split(";"); 
    } 

    Assert.isTrue(jsonKeysArray.length == propertyNameArray.length); 
    try 
    { 
     Method[] methods = new Method[ propertyNameArray.length ]; 
     for (Object obj : objs) 
     { 
      for (int i = 0; i < propertyNameArray.length; i++) 
      { 
       methods[ i ] = BeanUtils.getPropertyDescriptor(obj.getClass(), 
                   propertyNameArray[ i ]).getReadMethod(); 
      } 
      JSONObject json = new JSONObject(); 
      for (int i = 0; i < propertyNameArray.length; i++) 
      { 
       if (obj != null) 
        json.element(jsonKeysArray[ i ], 
            ReflectionUtils.invokeMethod(methods[ i ], obj)); 
      } 
      result.add(json); 
     } 

    } 
    catch (Exception e) 
    { 
     throw new RuntimeException(e); 
    } 

    return result; 
} 
相關問題