複雜 json 物件轉換成 java 物件

悬赏:20 发布时间:2008-07-03 提问人:dave0224 (初级程序员)

前端的 json 物件

[
  {
    "id": "1",
    "fields": [
      {"name": "age", "value": 10},
      {"name": "id", "value": "1"},
      {"name": "name", "value": "name-1"}
    ]
  },
  {
    "id": "2",
    "fields": [
      {"name": "age", "value": 10},
      {"name": "id", "value": "2"},
      {"name": "name", "value": "name-2"}
    ]
  },
]  

後端

String jsonString = request.getParameter("json"); // 前端傳來的 json 字串
List list = new ArrayList();

bindingValueToObject( list, jsonString ); // 將前端物件轉換成後端的物件


目前使用到 javalib ->  net.sf.json.JSONObject.fromObject(jsonString) 會發生錯誤.

有辦法自動轉換嗎

轉換後的物件為
List
  Record
    Field

采纳的答案

2008-07-03 marystone (中级程序员)

上面是用JSONLib跑出来的,
因为你Record类里面还有一个集合类型,在这里都是List类型,所以在再加上一个classMap让JSONLib深度转换。

JSONArray ja = JSONArray.fromObject(jsonString);

Map<String, Class<Field>> classMap = new HashMap<String, Class<Field>>();
classMap.put("fields", Field.class);

List<Record> list = JSONArray.toList(ja, Record.class, classMap);

提问者对于答案的评价:
謝謝

其他回答

JavaEye上面json方面的高手很少.

不过楼主可以参考一份资料:
http://www.javaeye.com/problems/675

这个是也是将json对象转换为Java类的,应该会对楼主有所帮助.
ham (架构师) 2008-07-03
可以用jettison 来解析 http://jettison.codehaus.org/
也可以用xstream 直接装换成java对象 xstream 是基于 jettison 的 http://xstream.codehaus.org/
kamhung (中级程序员) 2008-07-03
你接收到的json是数组,在转换成JAVA对象的时候要用JSONArray,

JSONArray ja =JSONArray.fromObject(jsonString);

JSONArray.toList(ja, Record.class);
marystone (中级程序员) 2008-07-03
这个是要写代码去做的,给你一个例子:
public class JsonModel
{
private String key;
private boolean multiple;
private List inputs;
private List conditions;
private String columns;

   下面是 setter和getter方法.......
}

public static JsonModel json2bean(String jsonStr)
{
  JSONObject jb = JSONObject.fromObject(jsonStr);
Map classMap = new HashMap();  
    classMap.put("inputs", InputsModel.class);
    classMap.put("conditions", Condition.class);
   
JsonModel ben = (JsonModel)JSONObject.toBean(jb, JsonModel.class,classMap);
if(ben==null)return null;
MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
Morpher dynaMorpher = new BeanMorpher( InputsModel.class, morpherRegistry );  
morpherRegistry.registerMorpher( dynaMorpher );  

List output = new ArrayList();  
if(ben.getInputs()!=null && ben.getInputs().size()>0 )
for( Iterator i = ben.getInputs().iterator(); i.hasNext(); ){
   output.add( morpherRegistry.morph( InputsModel.class, i.next() ) );  
}  
    ben.setInputs(output);

MorpherRegistry morpherRegistry2 = JSONUtils.getMorpherRegistry();
Morpher dynaMorpher2 = new BeanMorpher( Condition.class, morpherRegistry2 );  
morpherRegistry2.registerMorpher( dynaMorpher2 );  
   
    List outputConditions = new ArrayList();  
    if(ben.getConditions()!=null && ben.getConditions().size()>0 )
for( Iterator i = ben.getConditions().iterator(); i.hasNext(); ){
outputConditions.add( morpherRegistry2.morph( Condition.class, i.next() ) );  
}  
    ben.setConditions(outputConditions);
   
    return ben;
}

public static void main(String[] args)
{
  String str = "{\"key\": \"com.fsc.base.model.cpm.Company\", \"multiple\": false, \"inputs\": [{\"inputId\": \"InterfaceMangementForm:orderNum\", \"columnIndex\": \"1\"}], \"conditions\": [{\"name\": \"companyCd\", \"operator\": \"=\", \"value\": \"1120\"}, {\"name\": \"companyNm\", \"operator\": \"=\", \"value\": \"20000008\"}]}";
JsonUtil ju = new JsonUtil();
JsonModel jm = ju.json2bean(str);
System.out.println("condition="+jm.getConditions());
System.out.println("input="+jm.getInputs());
}
a3mao (初级程序员) 2008-07-03
public static void main(String[] args) {

String jsonString = "[{\"id\": \"1\",\"fields\": [{\"name\": \"age\", \"value\": 10},{\"name\": \"id\", \"value\": \"1\"},{\"name\": \"name\", \"value\": \"name-1\"}]},{\"id\": \"2\",\"fields\": [{\"name\": \"age\", \"value\": 10},{\"name\": \"id\", \"value\": \"2\"},{\"name\": \"name\", \"value\": \"name-2\"}]}]";

JSONArray ja = JSONArray.fromObject(jsonString);

Map<String, Class<Field>> classMap = new HashMap<String, Class<Field>>();
classMap.put("fields", Field.class);

List<Record> list = JSONArray.toList(ja, Record.class, classMap);

for (Record record : list) {
System.out.println("Record id:" + record.getId());

for (Field field : record.getFields()) {
System.out.println("Field name:" + field.getName());
}
}
}
marystone (中级程序员) 2008-07-03
首先建议使用成熟的JSON库,比如IBM的JSON4J,json.org的包。然后你再使用库提供的方法
alexcheng (初级程序员) 2008-07-03