2015-05-04 62 views
0

我正在使用JSON简单的库来解析Json格式。我怎样才能追加一些JSONArray?对于例如考虑以下jsonJSON-简单。附加到JSONArray

{ 
    "a": "b" 
    "features": [{/*some complex object*/}, {/*some complex object*/}] 
} 

我需要在features附加一个新条目。 我想创建这样的功能: -

public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){ 

    JSONArray arr = (JSONArray)jsonObj.get("features"); 

    //1) append the new feature 
    //2) update the jsonObj 
} 

如何实现上述代码中的步骤1 & 2?

回答

3

你可以试试这个:

public static void main(String[] args) throws ParseException { 

    String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}"; 
    JSONParser parser = new JSONParser(); 
    JSONObject jsonObj = (JSONObject) parser.parse(jsonString); 

    JSONObject newJSON = new JSONObject(); 
    newJSON.put("feature3", "value3"); 

    appendToList(jsonObj, newJSON); 

    System.out.println(jsonObj); 
    } 


private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) { 

     JSONArray arr = (JSONArray) jsonObj.get("features");   
     arr.add(toBeAppended); 
    } 

这将满足你的两个要求。

+0

这不符合我上面提供的方法签名。 – ishan3243

+0

不是创建一个新的'JSONObject'实例,而是使用'put'调用将方法中的第二个参数添加到'arr'中。 – asgs

+0

我编辑了我的答案以满足您的要求。 –

0

通过获取数组:jsonObj["features"],那么你可以在阵列中分配给它作为最后一个元素添加新的项目(jsonObj["features"].length是下一个免费的地方加入新的元素)

jsonObj["features"][jsonObj["features"].length] = toBeAppended; 

fiddle example

+0

OP在json-simple中寻求示例,而不是javascript。 – shahkalpesh

+0

好吧,10x澄清 – ItayB

+0

虽然这个源代码可能会提供一个答案,几个解释的话会有利于当前和未来的读者。 – Thom