简体   繁体   English

如何从Java中的URL获取JSON数据?

[英]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. 我已经签出了很多页面,但是大多数教程和脚本都使用这种JSON输出类型返回错误代码。 So how would I be able to extract the data from this JSON in Java?: 那么,我如何能够从Java中的JSON中提取数据?

[
  {
    "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: 如果要使用Gson,则首先声明用于容纳每个元素和子元素的类:

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: 然后,声明一个最外面的元素的数组(因为在这种情况下,JSON对象是一个JSON数组),并对其进行分配:

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

Then you simply access the elements of data . 然后,您只需访问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. 要记住的重要一点是,您声明的属性的名称和类型应与JSON字符串中的属性名称和类型匹配。 eg "id", "item_name" etc. 例如“ id”,“ item_name”等。

You could try JSON Simple 您可以尝试JSON简单
http://code.google.com/p/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. 如果您尝试在Java中序列化/反序列化json,我建议您使用Jackson。 http://jackson.codehaus.org/ 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后,您可以将JSON字符串反序列化为与JSON中的对象匹配的对象。

Jackson provides annotations that can be attached to your class which make deserialization pretty simple. Jackson提供了可以附加到您的类的注释,这使得反序列化非常简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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