0

Below is my JSON String. I am trying to extract hosts from it.

{"description":"DescA","process_running":"sf","hosts":{"dc1":["machineA","machineB"]}}

Since hosts is a JSON String in itself and I would like to extract that JSON String from it. I am using GSON here -

String ss = new String(bytes, Charset.forName("UTF-8"));

// here ss is the above JSON String

Map<String, Object> data = gson.fromJson(ss, Map.class); // parse

I was trying to use Map to deserialize but the result it coming like this in the data-

{description=DescA, process_running=sf, hosts={dc1=[machineA, machineB]}}

Is there any way, I can extract hosts in the JSON format?

3
  • You want to deserialize it from Json, but not actually? Best I can think of is deserialize the entirety into a custom object, then serialize back with just the hosts piece of that object. Commented Apr 2, 2014 at 19:54
  • First go to json.org and learn the JSON syntax. Then deserialize and access. (Based on your listing above, "host" is not an embedded JSON string but just a JSON object containing element "dc1" which is an array.) Commented Apr 2, 2014 at 20:02
  • @HotLicks: Thanks for correcting me. I mixed up few terminology. Commented Apr 2, 2014 at 20:18

1 Answer 1

1

The easiest way I can think of to do this would be to use gson to create a tree of json elements from your map, and ask it to give you just the hosts node:

    Map<String, Object> data = gson.fromJson(ss, Map.class); // parse

    JsonObject jsonTree = (JsonObject) gson.toJsonTree(data);
    String hostsJson = jsonTree.get("hosts").toString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.