Reputation: 91
Say I have a bunch of strings in json format
1. {"Name": Bob"}
2. {"Age" : 14}
3. {"address": "221 Baker street"}
Is there a way I can concatenate the json strings and create a json object in the end? i.e.
output -> {"Name": "Bob", "Age": 14, "Address": "221 Baker Street"}
I know I can parse each string and replace the "}" with a comma and that would work, but i was wondering if there was any inbuilt way of doing this
Thank you!
Upvotes: 0
Views: 610
Reputation: 7576
If you have Jackson on your classpath,
ObjectMapper mapper = new ObjectMapper();
Map<Object, Object> result = new HashMap<>();
result.putAll(mapper.readValue("{\"Name\": \"Bob\"}", Map.class));
result.putAll(mapper.readValue("{\"Age\": 14}", Map.class));
result.putAll(mapper.readValue("{\"address\": \"221 Baker street\"}", Map.class));
String concatenated = mapper.writeValueAsString(result);
Upvotes: 1