如何从Java中的JSON提取JSONArray和JSONObject

时间:2018-11-15 05:55:47

标签: java arrays json

如何从JSON提取JSON数组和JSON对象。

下面是输入:

{
    "messageName": "ReportCard",
    "orgId": "Org1",
    "comment": true,
    "Fields": [{
       "objectId": "1234-56789-asdv",
       "fieldId": "1245-7852-dhjd"
    },
    {
       "objectId": "1234-56hgjgh789-hjjhj",
       "fieldId": "12sdf45-78sfg52-dfjhjd"
    }]
}

我想要分别使用JSON数组和JSON对象,并且输出应类似于:

JSONArray

"Fields":[{ "objectId": "1234-56789-asdv",
           "fieldId": "1245-7852-dhjd"},{
           "objectId": "1234-56hgjgh789-hjjhj",
           "fieldId": "12sdf45-78sfg52-dfjhjd"}]

和JSON对象应类似于:

{
  "messageName": "ReportCard",
        "orgId": "Org1",
        "comment": true
}

2 个答案:

答案 0 :(得分:2)

如果您知道Java JSON API,这非常简单

String jsonString="{
    "messageName": "ReportCard",
    "orgId": "Org1",
    "comment": true,
    "Fields": [{
       "objectId": "1234-56789-asdv",
       "fieldId": "1245-7852-dhjd"
    },
    {
       "objectId": "1234-56hgjgh789-hjjhj",
       "fieldId": "12sdf45-78sfg52-dfjhjd"
    }]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject 
jo.put("messageName", jObject.getString("messageName").toString()); 
jo.put("orgId", jObject.getString("orgId").toString()); 
jo.put("comment", jObject.getString("comment").toString()); 

JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
    Map m = new LinkedHashMap(2); 
    JSONObject ArrayjObj = Fields.getJSONObject(i);
    m.put("objectId", ArrayjObj.getString("objectId").toString()); 
    m.put("fieldId", ArrayjObj.getString("fieldId").toString()); 
    // adding map to list 
    ja.add(m); 
 }
JSONObject fieldsObj = new JSONObject(); 
fieldsObj.put("Fields", ja); // Fields Array Created

有关JSON api,请参考this

答案 1 :(得分:1)

您可以将每个键的特定值提取到json对象中,然后放入单独的json数组中

String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}]   }";

 JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
  ja=  jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));