【问题标题】:How to parse JSON data form URL?如何解析 JSON 数据表单 URL?
【发布时间】:2016-06-08 11:48:07
【问题描述】:

您好,我正在尝试使用基本身份验证从 URL 解析 json 数据。数据来自服务器。

 HttpHost target = new HttpHost(targetUrl, 443, "https");
     HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
      .setProxy(proxy).setAuthenticationEnabled(true).build();
     HttpGet httpget = new HttpGet(targetURI + orderId + "/prod.json");
     httpget.setConfig(config);
response = httpClient.execute(target, httpget);
System.out.println(" Response ::" + EntityUtils.toString(response.getEntity()));

它显示json数据,如

[
  {
    "id": 1,
    "order_id": 100,
    "product_id": 113,
    "order_address_id": 1,
    "name": "Paper 002",
  }
]

我也有这个 Json 数据的 pojo 类。但是当我试图读取显示数据时,它会抛出错误。我使用 jackson 读取该数据读取数据的代码是。

String jsondata = EntityUtils.toString(response.getEntity());
               ObjectMapper objMapper = new ObjectMapper();
     ProDesc pd = objMapper.readValue(jsondata, ProDesc.class);
    System.out.println("** ID " + pd.getId());

那么如何使用jackson解析数据呢?我已经使用上面的代码显示了 json 数据。

【问题讨论】:

  • 您的 ProDesc 类的属性名称是否与 Json 中的属性名称相同?
  • 是的,我的属性名称与 comming json @kedarkamthe 相同
  • 你的ProDesc 类是什么样的?
  • @Narcis 我的 pojo 类就像:public class MyPojo { private int id;和 getter setter}

标签: java json parsing jackson


【解决方案1】:

您需要反序列化 ProDesc 对象列表,因为您的主要 JSON 是一个数组。

这就是我反序列化与 Jackson 2.1.4 类似的东西的方式:

List<ProDesc> proDescList = objMapper.readValue(jsondata, objMapper.getTypeFactory().constructParametricType(List.class, ProDesc.class));

编辑:如果您的 ProDesc 类仅包含 id 成员,您需要使用如下注释告诉 Jackson 忽略其他成员:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class ProDesc {

    private int id;

    public ProDesc(){}

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

【讨论】:

  • 我刚刚发布了在该特定版本中对我有用的代码。当然,可能还有其他方法可以做到这一点。很高兴它有帮助。
【解决方案2】:

我用这段代码解决了这个问题

 List<ProdDesc> proDescList = objMapper.readValue(jsondata, new TypeReference<List<ProDes>>() { }); 
for(ProDesc produ:proDescList)
{ System.out.println(produ.getId()); } 

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2015-05-29
    • 1970-01-01
    • 2019-10-21
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多