Java 将对象附加到 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23724221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:53:31  来源:igfitidea点击:

Java Append object to JSON

javajson

提问by redrom

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

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

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

      }
    ]

I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.

我正在尝试使用示例中的代码来做到这一点,但不幸的是,每次都覆盖整个对象。

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

How it should be right?

应该怎么做才对?

Put and accumulate everytime rewrite all previous values, but i would like to append this object:

每次重写所有以前的值时都进行放置和累积,但我想附加这个对象:

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

Into results parent.

进入结果父级。

BTW: I would like to do it without GSON.

顺便说一句:我想在没有 GSON 的情况下做到这一点。

Thanks for any help..

谢谢你的帮助..

采纳答案by Syam S

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?

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

With gson you can do like

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

}

回答by Munish Kapoor

Simple Approach

简单的方法

    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 Before Appending

追加前输出

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

OutPut After Appending

追加后输出

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

回答by Gagan Gowda

If you want to add new value to an Object you can try the below as well

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

Before:

前:

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

code :

代码 :

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

after:

后:

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