我是新来的,有一个问题,惊喜:D
我有一个JSON字符串,我想将其转换为List。
我的JSON字符串:
{
"results": [
{
"uri": "http://xxxxxx",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.438+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},
{
"uri": "http://yyyyyyy",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.560+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},]}
我如何用Java转换它?
编辑: 我的问题是“结果”根元素...... this 工作得很好。
答案 0 :(得分:1)
首先,您需要创建一个与JSON中的模型匹配的Java模型对象,例如:
public class MyClass {
private String uri;
private int downloadCount;
private ZonedDateTime lastDownloaded;
private int remoteDownloadCount;
private ZonedDateTime remoteLastDownloaded;
(getters and setters)
}
然后您可以使用像Jackson(https://github.com/FasterXML/jackson)这样的JSON解析器,使用Jackson ObjectMapper类(https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html)将您的JSON解析为此对象的实例列表:
ObjectMapper objectMapper = new ObjectMapper();
MyClass[] myClasses = objectMapper.readValue(jsonString, MyClass[].class);
答案 1 :(得分:1)
创建一个访问数据的类。
class ListElement {
public String uri;
public int downloadCount;
public String lastDownloaded;
public int remoteDownloadCount;
public String remoteLastDownloaded;
}
然后,解析json并获取列表并将其转换为list。
public static void main(String[] args) throws ParseException {
Gson gson = new Gson();
JsonElement list = new JsonParser().parse(json).getAsJsonObject().get("results");
List<ListElement> listObj = gson.fromJson(list, new TypeToken<List<ListElement>>() {}.getType());
System.out.println(listObj.size());
}
请注意,我使用的是String而不是ZonedDateTime。因为它是JsonObject的一个String(用引号括起来)。