简体   繁体   中英

How to get JSON data from an url in Java?

I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:

[
  {
    "user":{"id":"1","username":"user1"},
    "item_name":"item1",
    "custom_field":"custom1"
  },
  {
    "user":{"id":"2","username":"user2"},
    "item_name":"item2",
    "custom_field":"custom2"
  },
  {
    "user":{"id":"3","username":"user3"},
    "item_name":"item3",
    "custom_field":"custom3"
  }
]

If you want to use Gson, then first you declare classes for holding each element and sub elements:

public class MyUser {
  public String id;
  public String username;
}

public class MyElement {
  public MyUser user;
  public String item_name;
  public String custom_field;
}

Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:

MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);

Then you simply access the elements of data .

The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. eg "id", "item_name" etc.

You could try JSON Simple
http://code.google.com/p/json-simple/

Example:

JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);

for (int i = 0; i < jsonArray.size(); i++) {
    JSONObject obj = (JSONObject) jsonArray.get(i);
    //Access data with obj.get("item_name")
}

Just be careful to check for nulls/be careful with casting and such.

If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/

Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.

Jackson provides annotations that can be attached to your class which make deserialization pretty simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM