gpt4 book ai didi

java - 如何使用多级数组遍历 Gson 对象

转载 作者:行者123 更新时间:2023-12-01 19:43:57 27 4
gpt4 key购买 nike

我正在尝试使用 Gson 库获取 jSon items>item>image>images>transparent 内的参数。这个想法是捕获 transparenttransparent_blanktransparent_dark。但我不知道如何获得这些值,目前我创建了以下内容:

Json

{ 
"date_layout":"day-month-year",
"lastupdate":1547596830,
"items":[{
"name":"Cleans Cuts",
"featured":"true",
"item":{
"image":"http:www.domain.com/unwanted_image.jpg",
"images":{
"transparent":"http:www.domain.com/desired_image1.jpg",
"transparent_blank":"http:www.domain.com/desired_image2.jpg",
"transparent_dark":"http:www.domain.com/desired_image3.jpg"
}
}
},
{
"name":"Cleans Cuts",
"featured":"true",
"item":{
"image":"http:www.domain.com/unwanted_image.jpg",
"images":{
"transparent":"http:www.domain.com/desired_image1.jpg",
"transparent_blank":"http:www.domain.com/desired_image2.jpg",
"transparent_dark":"http:www.domain.com/desired_image3.jpg"
}
}
}]
}

.MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String url = "http://www.example.com/file.json";

Request request = new Request.Builder()
.url(url)
.build();

Response response = client.newCall(request).execute();
if(response.isSuccessful()){
String response_jSon = response.body().string();
Gson gson = new Gson();
Datos datosFinal = gson.fromJson(response_jSon, Datos.class);
for (int i=0; i<datosFinal.items.size(); i++){
Log.d("msg_2", datosFinal.items.get(i).name);
}
}

我只能访问您在 .MainActivity 日志中看到的项目。

Json 的类对象

Datos.java

public class Datos {
public String date_layout;
public Int lastupdate;
List<items> items;
}

items.java

public class items {
public String name;
}

最佳答案

json 不是很干净,我建议您重新设计该 json 字符串的生成方式,但如果您仍然想在不重新设计 json 的情况下获取这些值,则需要更改您的 Items 类:

`public class items {
public String name;
public String featured;
public Item item;
}`

然后您需要创建另一个名为Item的类

`public class Item{
public String image;
public Image images;
}`

您还需要创建一个 Image 类,如下所示:

`public class Image {
public String transparent;
public String transparent_blank;
public String transparent_dark;
}`

然后您可以在循环中记录这些值:

`Datos datosFinal = gson.fromJson(response_jSon, Datos.class);
for (int i=0; i<datosFinal.items.size(); i++){
Log.d("msg_2", datosFinal.items.get(i).item.images.transparent);
Log.d("msg_2", datosFinal.items.get(i).item.images.transparent_blank);
Log.d("msg_2", datosFinal.items.get(i).item.images.transparent_dark);
}`

虽然这可能有效,但我强烈建议您重新设计您的 json 并使其更易于维护。

关于java - 如何使用多级数组遍历 Gson 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54253760/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com