user2896040
user2896040

Reputation: 5

Get JSONobjects from string

So i have a string which contains multiple JSONobjects and looks like this:

[{"one":"1","two":"2","three":"3"}, {"one":"4","two":"5","three":"6"}, {"one":"7","two":"8","three":"9"}]

How can i iterate through this string using java and get every object? Is it possible using JSON api, or i should make parser by myself?

Upvotes: 0

Views: 67

Answers (3)

Cahit Gungor
Cahit Gungor

Reputation: 1497

It is obvious that you should use a JSON library. Existing libraries are tested and validated. In very rare conditions you may need to write your own parser, your own implementation. If that is the case, I think you should double check your design. Because you might be doing something wrong if the existing library is in conflict with your design.

Library selection depends on your environment and your performance requirements. In my case, Spring3 is the environment and the JSON objects are huge (10-20MB), and inserts occur on existing JSON objects. We prefer Jackson. Jackson's performance is outstanding. An independent performance comparison is in here. You will see that the Jackson outperforms GSon in here.

Upvotes: 0

Braj
Braj

Reputation: 46841

GSON library is a good option to convert java object to json string and vise versa.

In your case it's a List of Object.

sample code:

class MyPOJO {
    private String one;
    private String two;
    private String three;
    // getter & setter
}

String jsonString = "[{\"one\":\"1\",\"two\":\"2\",\"three\":\"3\"}, {\"one\":\"4\",\"two\":\"5\",\"three\":\"6\"}, {\"one\":\"7\",\"two\":\"8\",\"three\":\"9\"}]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(jsonString, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));

Note: The name of variable in your java POJO class should be same as JSON string.

Find more examples...

Upvotes: 2

Jacob Amsalem
Jacob Amsalem

Reputation: 109

You Should defiantly use the Json API, you can download the jar from here and simply use

JSONArray myArray = new JSONArray(yourString);
for (int i=0; i < myArray.length(); i++)
{
    JSONObject currentOb = myArray.get(i);
    doSomthing(currentOb);
}

Upvotes: 1

Related Questions