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!

3
  • What should the behavior be if you're merging {"Name": "Bob"} and [10]? Commented Jun 14, 2016 at 23:21
  • all json string objects coming in should be of the format key : value pair. (theres a check for this before).
    – Akshay
    Commented Jun 14, 2016 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.
    – shmosel
    Commented Jun 14, 2016 at 23:24

1 Answer 1

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.