我想使用GSON库从Json Object中提取数组。
我已经尝试创建类并让Gson库完成工作,但是在这种情况下,它是行不通的。
提取数据的类
public class Images {
private Image[] images;
public class Image {
private String url;
public Image(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
public Images(Image[] images) {
this.images = images;
}
public Image[] getImages() {
return images;
}
}
示例数据
...
,
"images": [
{
"url": "https://a.allegroimg.com/original/030516/a867b9dd4021b15678fc03a3981b"
},
{
"url": "https://a.allegroimg.com/original/03da09/19740f7147ad929609cc2bcc499e"
},
{
"url": "https://a.allegroimg.com/original/03198b/c024c7e448cab876bb49ad055567"
},
{
"url": "https://a.allegroimg.com/original/039fee/64bae4c64dac89e5b5b4d001c2ca"
}
],
...
我遇到错误:“ com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但在行1列283路径$ .items.promoted [0] .images中为BEGIN_ARRAY”
我正在寻求从json对象提取数据的帮助。
我只需要删除类“ Images”并将“ URL”从Json保存到Image []
答案 0 :(得分:0)
期望BEGIN_OBJECT,但在行1列283路径$ .items.promoted [0] .images中是BEGIN_ARRAY
问题是由于包装器类Images
引起的。从错误中,我认为您的对象是这样的:
class Promoted {
private Images images;
..
}
class Images {
private Image[] images;
}
在当前形式下,您可以解析的json是:
...
,
"images": {
"images": [
{
"url": "https://a.allegroimg.com/original/030516/a867b9dd4021b15678fc03a3981b"
},
{
"url": "https://a.allegroimg.com/original/03da09/19740f7147ad929609cc2bcc499e"
},
{
"url": "https://a.allegroimg.com/original/03198b/c024c7e448cab876bb49ad055567"
},
{
"url": "https://a.allegroimg.com/original/039fee/64bae4c64dac89e5b5b4d001c2ca"
}
]
}
...
相反,您可以直接将数组Image[]
嵌入父对象(没有包装类):
class Promoted {
private Image[] images;
..
}
答案 1 :(得分:-1)
您可以使用DSM库。通过使用它,您可以在读取JSON数据时提取JSON的一部分。
首先,您必须以yaml格式定义映射。
映射定义:
result:
type: array # expect result as array
path: /images
fields:
url:
使用DSM读取数据。
DSM dsm=new DSMBuilder(new File("path/to/config.yaml")).create();
Object object=dsm.toObject(new File("path/to/data.json");
System.out.println(object);
以下是输出:
[{url=https://a.allegroimg.com/original/030516/a867b9dd4021b15678fc03a3981b}, {url=https://a.allegroimg.com/original/03da09/19740f7147ad929609cc2bcc499e}, {url=https://a.allegroimg.com/original/03198b/c024c7e448cab876bb49ad055567}, {url=https://a.allegroimg.com/original/039fee/64bae4c64dac89e5b5b4d001c2ca}]
如果要获取所有 url 字段作为列表,则可以按以下方式收取映射定义的费用。
result:
type: array
path: /images/url
此映射的输出为:
[https://a.allegroimg.com/original/030516/a867b9dd4021b15678fc03a3981b, https://a.allegroimg.com/original/03da09/19740f7147ad929609cc2bcc499e, https://a.allegroimg.com/original/03198b/c024c7e448cab876bb49ad055567, https://a.allegroimg.com/original/039fee/64bae4c64dac89e5b5b4d001c2ca]