2015-09-25 135 views
1

我是一个在Java中的新手,我正在研究如何解析json在java中的对象。解析json到对象

我有以下的Json内容:

{ 
"objects": [ 
    { 
     "type": "image", 
     "left":0, 
     "top":0, 
     "width":787, 
     "height":1165, 
     "src":"image/16_011020002_000_bk.PNG", 
     "replaceable":false, 
     "lockObject":false 
    }, 
    { 
     "type": "image", 
     "left":70, 
     "top":54, 
     "width":669, 
     "height":469, 
     "src":"image/16_011020002_000_il.PNG", 
     "replaceable":false, 
     "lockObject":false 
    }, 
    { 
     "left":70, 
     "top":54, 
     "width":669, 
     "height":469, 
     "direction":"v", 
     "fontFamily":"KaitiEG4-Medium-SJIS", 
     "fill":"#55626C", 
     "text":"旧年中は大変お世話になり\nありがとうございました\n本年も相変わらずご支援のほど\nお願い申し上げます\n\n       平成二十八年 元旦", 
     "textAlign":"left", 
     "lockObject":false 
    }, 
    { 
     "left":70, 
     "top":54, 
     "width":669, 
     "height":469, 
     "direction":"v", 
     "fontFamily":"LeisuEG4-Medium-SJIS", 
     "fill":"#55626C", 
     "text":"謹んで\n 初春のお慶びを\n   申し上げます", 
     "textAlign":"left", 
     "lockObject":false 
    } 
] 
} 

如何设计对象为这​​个JSON和如何解析JSON到该对象? 帮我解决这个问题。谢谢!

+0

阅读杰克逊图书馆 – Jens

+0

标记我的答案为答案,所以如果有人会检查出这个问题,将立即找到答案 – dklos

回答

2

我希望它会帮助你...!
使用Jackson-

JSONArray objects=new JSONObject(jsondata).getJSONArray("objects"); 
    for(int i=0;i<objects.length();i++){ 
     JSONObject object=objects.getJSONObject(i); 
     System.out.println("value of left=="+object.getString("left")); 
     System.out.println("value of top=="+object.getString("top")); 

    } 
+0

我认为GSON对于新手来说可能更简单 – dklos

+0

非常感谢! @vikas balyan – user3161772

0

按照您的问题其似乎是表示类型的对象的JSON数据的数组。

要解析数据,我们可以使用d__k提到的上述两个解析器。

I have been using Jackson and we have a ObjectMapper class which converts the data in the specified type. We can use ObjectMapper#readValue to read the data into java object. 

请在this链接处查找更多信息。