已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。
去年关闭了。
Improve this question
{
"products": [{
"electronics": {
"productId": "A2",
"title": "earphone",
"productDescription": "Description",
"imageUrls": {
"url1": "url1",
"url2": "url2",
"url3": "url3"
}
},
"electronics": {
"productId": "A2",
"title": "mic",
"productDescription": "Description",
"imageUrls": {
"url1": "url1",
"url2": "url2",
"url3": "url3"
}
}
}
]
}
Package 函数模型类(& M):
public class Product {
@SerializedName("productId")
private String productId;
@SerializedName("title")
private String title;
@SerializedName("productDescription")
private String productDescription;
@SerializedName("imageUrls")
private List<ImageUrl> imageUrls;
// Setters & Getters
}
public class ImageUrl {
@SerializedName("url1")
private String url1;
@SerializedName("url2")
private String url2;
@SerializedName("url3")
private String url3;
// Setters & Getters
}
public class ProductWrapper {
@SerializedName("electronics")
private List<Product> mData;
// Setters & Getters
}
解串器:
public class MyDeserializer<T> implements JsonDeserializer<T> {
@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// Get the "products" element from the parsed JSON
JsonElement products = jsonElement.getAsJsonObject().getAsJsonArray("products");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(products, type);
}
}
改造示例
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Blog.class, new MyDeserializer())
.create();
retrofit = new Retrofit
.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
以上代码不起作用。
2条答案
按热度按时间daupos2t1#
我建议在这种情况下,你可以使用一些实用工具,如:https://www.jsonschema2pojo.org/
在这里你可以粘贴你的JSON。选择“源类型:“-〉JSON选择“注解样式:“-〉GSON
点击预览,您将看到以下POJO类结构,它将以正确方式生成
然后创建
Retrofit
示例,您将只需要这个。在本例中,您对改型调用的响应类型将是
Example
类,即关键字products
所在的根类。bvjveswy2#
根据您发布的代码,类ProductWrapper需要一个Blogs列表,但是在传入的JSON中,有一个产品列表。因此,将
mData
更改为:private List<Product> mData;
个另外,现在还不需要自定义反序列化。如上所述,您应该尝试使用一个工具。如果您想使用Kotlin,可以使用一个类似的工具:https://www.json2kotlin.com/