使用此存储库:https://github.com/dds861/Retrofit2 并遵循本教程:https://medium.com/@dds861/json-parsing-using-retrofit-and-recycleview-2300d9fdcf15 代码工作正常,但如果我更改了JsonResponse类返回的数组的名称,它会给我一个空指针异常。 这是Json返回的响应:
{ "android": [ { "ver": "1.5", "name": "Cupcake", "api": "API level 3" }, { "ver": "1.6", "name": "Donut", "api": "API level 4" }, { "ver": "2.0 - 2.1", "name": "Eclair", "api": "API level 5 - 7" }, { "ver": "2.2", "name": "Froyo", "api": "API level 8" }, { "ver": "2.3", "name": "Gingerbread", "api": "API level 9 - 10" }, { "ver": "3.0 - 3.2", "name": "Honeycomb", "api": "API level 11 - 13" }, { "ver": "4.0", "name": "Ice Cream Sandwich", "api": "API level 14 - 15" }, { "ver": "4.1 - 4.3", "name": "JellyBean", "api": "API level 16 - 18" }, { "ver": "4.4", "name": "KitKat", "api": "API level 19" }, { "ver": "5.0 - 5.1", "name": "Lollipop", "api": "API level 21 - 22" }, { "ver": "6.0", "name": "Marshmallow", "api": "API level 23" }, { "ver": "7.0 - 7.1", "name": "Nougat", "api": "API level 24 - 25" } ] }
JsonResponse类中的数组名称是android,它与响应中对象的名称相同。如果我将其更改为类似androids,它会崩溃。谁能解释一下呢?
答案 0 :(得分:1)
您可以更改pojo类中的数组名称,但应将序列化名称保留为android。
答案 1 :(得分:1)
如果您想在POJO对象中使用其他名称,则需要使用@SerializedName注释。
例如,在您的情况下,您需要执行以下操作:
public class POJOClass {
//...
@SerializedName("android")
private ArrayList androids;
//...
}
现在您可以拥有一个具有所需名称的arrayList。使用此注释,您可以将json中的元素与变量链接。
答案 2 :(得分:1)
您可以使用@SerializedName批注为变量指定不同的名称
例如 -
public class POJOClass {
@SerializedName("android") //here use name same as in json to let them map.
private ArrayList androidList; //use name as you want here
}