简体   繁体   English

Java将对象附加到JSON

[英]Java Append object to JSON

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.. 谢谢你的帮助..

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"}]} . 这将打印{"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 有了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);
    }

}

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"}]}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM