Java Append object to JSON

后端 未结 3 1399
深忆病人
深忆病人 2021-01-19 07:13

I would like to append JSON object to existing JSON array to get data structure like this.

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


        
3条回答
  •  离开以前
    2021-01-19 07:45

    There isnt any problem with your code. It does append

    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);
    

    This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}. Isnt this what you are expecting?

    With gson you can do like

    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);
        }
    
    }
    

提交回复
热议问题