0

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!

Akshay
  • 91
  • 9
  • What should the behavior be if you're merging `{"Name": "Bob"}` and `[10]`? – David Ehrmann Jun 14 '16 at 23:21
  • all json string objects coming in should be of the format key : value pair. (theres a check for this before). – Akshay Jun 14 '16 at 23:23
  • Android has a (primitive) built-in JSON library, but if you're using plain Java, you'll need to [import a JSON library](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java). – shmosel Jun 14 '16 at 23:24

1 Answers1

1

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);
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40