0

I've some json data like this:

[{"id":"someid","name":"some name"}, {"id":"some other id", "name":"a name"}]

I want to get the json objects in the above array aslist of strings like

(each string is json object in string form, (List<String>))

(For simplicity

 [ {"id":"someid","name":"some name"},{"id":"some other id", "name":"a name"} 

I tried using jackson's TypeReference> but it is causing consituents parts like id, someid into the list elements instead of making each json object a string element.

I also tried using jackson TypeReference>, this time I'm getting the number of objects correctly, but all the double quotes are gone and ':' are converted to '=', so it converted to java object not a json raw string.

I'm getting like [{id=someid,name=somename},{id=some other id, name=a name}]

I'm interested to know how to do this using Jackson library.

Any help would be appreciated.

pinkpanther
  • 4,770
  • 2
  • 38
  • 62
  • please post the code you have tried, we will make an effort to fix it but no one will do the work for you – Sharon Ben Asher Jul 08 '15 at 09:04
  • 2
    I do not understand what is the desired output. a json object is not a list, it is a map of keys and values. please give an example of the desired list contents – Sharon Ben Asher Jul 08 '15 at 09:06
  • @sharonbn I want to convert a json array to list of string such that each is string is a raw json object of the original json array. – pinkpanther Jul 08 '15 at 10:13

3 Answers3

1

Use org.json.simple.parser.JSONParser to parse JsonArray String to JsonArray Object.

    JSONParser parser = new JSONParser();
    JSONArray arr = (JSONArray) parser.parse(jsonArray);
    List<String> list = new ArrayList<String>();
    for (Object jsonObject : arr) {
        System.out.println("jsonObject>>"+jsonObject);
        list.add(jsonObject.toString());
    }

Here the prepared list contains json(raw) strings as you desire. Hope it will help you

Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73
  • 1
    Thanks for the answer.. equivalently I could achieve it using JSONArray. But I'm interested to know if there is a way to do it using Jackson library – pinkpanther Jul 08 '15 at 10:19
0

I was able to achieve the desired to result using JSONArray from json library. For any one comes across this question I'm posting this.

JSONArray jsonArray = new JSONArray(jsonString);
List<String> list = new ArrayList<String());
for(int i = 0 ; i < jsonArray.length();i++){
    list.add(jsonArray.getJSONObject(i));
}

However I'm still interested to know how to do this using Jackson library alone.

pinkpanther
  • 4,770
  • 2
  • 38
  • 62
0

jsonArray.getJSONObject() method returns an instance of JSONObject. So, you either need to change the return value to List<JSONObject> or within your for loop, call jsonArray.getJSONObject(i).toString() to return a List<String>

ironman
  • 1
  • 1