2

I have an external parsed List type which is a json array, indeed this call

list.toString()

gives me this:

[{name=prop1, content=<something>},{name=prop2, content=<something>}]

The content could be anything, an array, a string, an int... So I'd like to map that json array to something like

HashMap<String,Object> converted;

This would allow me to do this:

converted.get("prop1"); //this will give me the <something>

how could I do that?

5
  • 2
    Careful, that isn't JSON. Commented Mar 25, 2014 at 19:22
  • I believe you cannot do that directly... Either go through a parser, create POJOs or parse the JSON directly Commented Mar 25, 2014 at 19:23
  • It is a json array, how come it isn't json? Commented Mar 25, 2014 at 19:27
  • If they're just Strings, you could use something like [MapSplitter](./guava/src/com/google/common/base/). Commented Mar 25, 2014 at 19:28
  • 1
    Just because it has [] and {}, doesn't mean it is JSON. Look into the JSON format. Commented Mar 25, 2014 at 19:28

1 Answer 1

2

Try this using JSON Parser. Get the JSON lib from here json.simple

Map<String, Object> map = new HashMap<>();

JSONParser parser = new JSONParser();

try {

  Object obj = parser.parse(list);

  JSONArray jsonArray = (JSONArray)obj;

  Iterator<JSONObject> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
       JSONObject jsonObj = iterator.next();
      String name = (String) jsonObject.get("name");
       Object content = (Object) jsonObject.get("content");
       map.put(name, content);
  }
} catch (ParseException p) { }
Sign up to request clarification or add additional context in comments.

1 Comment

no..i forgot to add the code for parsing...now i have edited my code

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.