如何在 Android 中使用 Jackson 从 JSONArray url 获取 java 对象

How to get java objects from JSONArray url using Jackson in Android

这是我来自 URL 的 JSON https://api.myjson.com/bins/142jr

[
  {
    "serviceNo":"SR0000000001",
    "serDate":"17",
    "serMonth":"DEC",
    "serYear":"2015",
    "serTime":"02.30 AM",
    "serApartmentName":"Galaxy Apartments"
  },
  {
    "serviceNo":"SR0000000002",
    "serDate":"19",
    "serMonth":"JUN",
    "serYear":"2016",
    "serTime":"03.30 AM",
    "serApartmentName":"The Great Apartments"
  }
]

我有一个 ListView 我想从在线 JSON 填充详细信息,上面我给出了一个 link 和示例 json 任何人在 java[= 中给出示例 jackson 代码15=]

感谢提前, 拉杰什·拉金迪兰

如果您将其作为 http 响应获取,那么我建议使用 spring 用于 android 的休息模板。 它支持消息转换器。这样编组和解组的责任。

[更新] 这是相同的博客:http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program

有关更多详细信息,请参阅文档:

http://docs.spring.io/spring-android/docs/current/reference/html/rest-template.html

要使用 jackson,您需要创建一个模型 class:

[
  {
    "serviceNo":"SR0000000001",
    "serDate":"17",
    "serMonth":"DEC",
    "serYear":"2015",
    "serTime":"02.30 AM",
    "serApartmentName":"Galaxy Apartments"
  },
  {
    "serviceNo":"SR0000000002",
    "serDate":"19",
    "serMonth":"JUN",
    "serYear":"2016",
    "serTime":"03.30 AM",
    "serApartmentName":"The Great Apartments"
  }
]

对于上述 json 模型 class 将是:

public class SomeClass {
 private String serviceNo;
 private String serDate;
 private String serMonth;
 private String serYear;
 private String serTime;
 private String serApartmentName;

 @JsonProperty("serviceNo") //to bind it to serviceNo attribute of the json string
 public String getServiceNo() {
  return serviceNo;
 }

 public void setServiceNo(String sNo) { //@JsonProperty need not be specified again
  serviceNo = sNo;
 }

 //create getter setters like above for all the properties.
 //if you want to avoid a key-value from getting parsed use @JsonIgnore annotation

}

现在,只要你将上面的 json 作为字符串存储在变量中,就说 jsonString 使用下面的代码来解析它:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse
ArrayList<SomeClass> results = mapper.readValue(jsonString,
   new TypeReference<ArrayList<ResultValue>>() { } );

结果现在应该包含两个 SomeClass 对象,上面 json 被解析为各自的对象。

PS: 好久没用Jackson解析了,这段代码可能需要改进一下。