-1

I need to alter a existing JSON with few new fields. Example existing JSON

{ "a":1, "b":3 , "c":5 }

I want to add new field after "b":3

{ "a":1, "b":3, "s":4, "c":5 }

When I try adding a new field, it gets added over the end of the existing message like below

{ "a":1, "b":3, "c":5, "s":4 }

Please help me with right approach.

Updated code used for adding new node

Object obj = parser.parse(jsonStr);
JsonObject jsonObject = (JsonObject) obj;
Gson gson = new GsonBuilder().setPrettyPrinting().create();  
JsonElement jsonElement = gson.toJsonTree(jsonObject);
jsonElement.getAsJsonObject().addProperty("s", 4);
jsonStr = gson.toJson(jsonElement);
ESri
  • 11
  • 1
  • 6
  • 1
    You state, *"When I try..."*, but you don't show us the code attempt, making it extremely difficult to know what you may be doing wrong. Please [edit] your question and fix this problem. – Hovercraft Full Of Eels Mar 23 '21 at 18:13
  • A JSON content is a STRING, when you load the structure depending of your language it becomes, either a Map, a List, ..., you don't change the JSON directly, never as it's a string – azro Mar 23 '21 at 18:13
  • Sorry as I missed to add the code. I have updated the code now. – ESri Mar 24 '21 at 01:54
  • Please provide if there is better approach to edit using java or javascript – ESri Mar 24 '21 at 02:01

2 Answers2

0

The two JSON strings are equivalent as JSON object elements do not have an order. As long as you are creating the JSON output via some serialization mechanism (you did not state how you are "adding a new field"), there is usually no way to enforce a certain order.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • I agree json object do not have order but for our requirement we have subsequent subnodes for node "c" . For better view, I wanted the new node to be added before "c" – ESri Mar 24 '21 at 01:53
0

You can parse jsonStr to a LinkedHashMap, then add new field after "b":3, and then use gson.toJson(your LinkedHashMap).

Fly King
  • 91
  • 1
  • 4
  • Thanks for the reply. I was able to covert the json string to Map. Can you help me on How can I add a new field after "b":3 , I am trying Map.put() and it adds at the end. – ESri Mar 24 '21 at 08:44
  • check this. [How to add element at specific index/position in LinkedHashMap?](https://stackoverflow.com/a/44483952/10558255) – Fly King Mar 25 '21 at 09:21