How to get JSON data from an url in Java?

2019-01-27 01:23发布

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"
  }
]

3条回答
我想做一个坏孩纸
2楼-- · 2019-01-27 02:08

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. e.g. "id", "item_name" etc.

查看更多
3楼-- · 2019-01-27 02:10

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.

查看更多
The star\"
4楼-- · 2019-01-27 02:19

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.

查看更多
登录 后发表回答