Как эффективно объединить две строки JSON на основе общего ключаJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как эффективно объединить две строки JSON на основе общего ключа

Сообщение Anonymous »


I have two JSON strings which are essentially arrays of JSONObject. The two JSON strings have below structure and keys:

JSON-1:

[ { "title": "ABC", "edition": 7, "year": 2011 }, { "title": "DEF", "edition": 2, "year": 2012 }, { "title": "XYZ", "edition": 3, "year": 2013 } ] And, JSON-2:

[ { "title": "ABC", "price": "20" }, { "title": "DEF", "price": "20" }, { "title": "XYZ", "price": "20" } ] Both these JSONs have a common key "title" based on which I want to merge these two JSONs, either merging JSON-2 values into JSON-1 or creating a JSON object with the merged result.

The merged result should look like below:

[ { "title": "ABC", "edition": 7, "year": 2011, "price": "20" }, { "title": "DEF", "edition": 2, "year": 2012 "price": "20" }, { "title": "XYZ", "edition": 3, "year": 2013 "price": "20" } ] How can I achieve this by minimum looping and minimum object creation? I also can not use entity/model classes. The idea is to do it without creating any model classes.

Note: I cannot use Gson because I don't have the approval to use the same.
  • I tried to use List listObj = objectMapper.readValue(jsonOneString, new TypeReference(){});, but I am getting an unknown property exception.
  • I tried JsonNode node = objectMapper.readTree(jsonOneString);, but I cannot proceed much further with this approach.

I know what I am doing here is highly inefficient, so looking for ways which will use no entity class, minimum new object creation and minimum loops. Kindly advise.

UPDATE: I updated the below code with a slight modification:
if (json1elem.get("title")!=null && json2elem.get("title")!=null && json1elem.get("title").equals(json2elem.get("title"))) { // }

Источник: https://stackoverflow.com/questions/736 ... common-key
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»