如何从Java中的URL获取JSON数据? [英] How to get JSON data from an url in Java?

查看:755
本文介绍了如何从Java中的URL获取JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经签出了很多页面,但是大多数教程和脚本都使用这种JSON输出类型返回错误代码.那么我将如何从Java中的JSON中提取数据呢?:

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

推荐答案

如果要使用Gson,则首先声明用于容纳每个元素和子元素的类:

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;
}

然后,声明最外层元素的数组(因为在这种情况下,JSON对象是JSON数组),并对其进行分配:

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);

然后,您只需访问data的元素.

Then you simply access the elements of data.

要记住的重要一点是,您声明的属性的名称和类型应与JSON字符串中的属性名称和类型匹配.例如"id","item_name"等

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.

这篇关于如何从Java中的URL获取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆