سؤال

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below

[{"styleId":94,
  "status":"verified",
  "abv":"4.2",
  "name":"Bud Light"}]

Here is my current code

       JSONParser parser = new JSONParser();

       Object obj = parser.parse(inputLine);

       JSONObject jsonObject = (JSONObject) obj;

       Long currPage = (Long)jsonObject.get("currentPage");
       System.out.println(currPage);


       JSONArray jArray = (JSONArray)jsonObject.get("data");
       System.out.println(jArray);

inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.

Thanks for the help in advanced!

هل كانت مفيدة؟

المحلول 2

just use Gson . it works well out of the box with any object type you supply.

This is an example from the user's guide:

int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

نصائح أخرى

To iterate in a JSONArray you need to go through each element in a loop.

int resultSize = jArray.length();           
JSONObject result;

for (int i = 0; i < resultSize; i++) {
    result = resultsArray.getJSONObject(i);
    String name = result.getString("name");

    // do whatever you want to do now...
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top