Java将对象追加到JSON

时间:2014-05-18 16:27:56

标签: java json

我想将JSON对象附加到现有的JSON数组以获取这样的数据结构。

"results":[
      {
         "lat":"value",
         "lon":"value"
      }, 
      {
         "lat":"value",
         "lon":"value"

      }
    ]

我尝试使用示例中的代码来执行此操作,但不幸的是,每次都会覆盖整个对象。

    Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
                AppHelper helper = new AppHelper(ctx);
                JSONObject mainObject = new JSONObject(jsonDataString);
                JSONObject valuesObject = new JSONObject();
                JSONArray list = new JSONArray();
                //putv given values to the JSON
                valuesObject.put("lat", lat.toString());
                valuesObject.put("lon", lon.toString());
                valuesObject.put("city", city);
                valuesObject.put("street", street);
                valuesObject.put("date", helper.getActualDateTime());
                valuesObject.put("time", helper.getActualDateTime());
                list.put(valuesObject);
                //mainObject.put("values", list);
                mainObject.accumulate("values", list);
                saveJsonData(ctx, mainObject.toString(),"positions");

它应该如何?

每次重写所有以前的值时放入并累积,但我想追加这个对象:

{
     "lat":"value",
     "lon":"value"
  },

进入结果父母。

BTW:我想在没有GSON的情况下这样做。

感谢您的帮助..

3 个答案:

答案 0 :(得分:3)

您的代码没有任何问题。它确实附加

String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);

这会打印{"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}。 这不是你期待的吗?

使用gson你可以这样做

import com.google.gson.Gson;
import com.google.gson.JsonObject;


public class AddJson {

    public static void main(String[] args) {
        String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
        Gson gson = new Gson();
        JsonObject inputObj  = gson.fromJson(json, JsonObject.class);
        JsonObject newObject = new JsonObject() ;
        newObject.addProperty("lat", "newValue");
        newObject.addProperty("lon", "newValue");
        inputObj.get("results").getAsJsonArray().add(newObject);
        System.out.println(inputObj);
    }

}

答案 1 :(得分:2)

简单方法

    String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
    System.out.println(jsonData);
    try {
        JSONArray result = new JSONObject(jsonData).getJSONArray("results");
        result.getJSONObject(0).put("city","Singapore");
        jsonData = "{\"results\":"+result.toString()+"}";
        System.out.println(jsonData);
    } catch (JSONException e) {
        e.printStackTrace();
    }

追加前的OutPut

{"results":[{"lat":"value","lon":"value" }]} 

追加后的OutPut

{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}

答案 2 :(得分:0)

如果您想为对象添加新值,也可以尝试以下方法

之前:

{
    "Name": "EnCoMa",
    "Manager": "Abhishek Kasetty"
 }

代码:

JsonFactory factory = new JsonFactory();      
ObjectMapper mapper = new ObjectMapper(factory);
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
    ObjectNode node = (ObjectNode) mapper.readTree(json);
    node.putPOJO("new Key","new value")

之后:

{
    "Name": "EnCoMa",
    "Manager": "Abhishek Kasetty",
    "new Key": "new value"
}