使用Gson库,如何将JSON字符串转换为自定义类JsonLog的数组列表?基本上,JsonLog是由我的Android应用程序制作的不同类型的日志实现的接口——短信日志、通话日志、数据日志——这个数组列表是所有这些日志的集合。第6行总是出错。
public static void log(File destination, JsonLog log) {
Collection<JsonLog> logs = null;
if (destination.exists()) {
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(destination));
logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6
// logs.add(log);
// serialize "logs" again
}
}
编译器似乎不明白我引用的是一个类型化的数组列表。我该怎么办?
你可以使用TypeToken将json字符串加载到一个自定义对象中。
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
文档:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for List<String>, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as Class<?> or List<? extends CharSequence>.
科特林:
如果你需要在Kotlin中这样做,你可以这样做:
val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)
或者你可以从其他选项中看到这个答案。
科特林
data class Player(val name : String, val surname: String)
val json = [
{
"name": "name 1",
"surname": "surname 1"
},
{
"name": "name 2",
"surname": "surname 2"
},
{
"name": "name 3",
"surname": "surname 3"
}
]
val typeToken = object : TypeToken<List<Player>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)
OR
val playerArray = Gson().fromJson(json, Array<Player>::class.java)
假设,你有一条这样的弦。
"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"
然后你可以通过Gson把它转换成数组列表
var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()
您的HotelInfo类应该是这样的。
import com.squareup.moshi.Json
data class HotelInfo(
@Json(name="cityName")
val cityName: String? = null,
@Json(name="id")
val id: Int? = null,
@Json(name="hotelId")
val hotelId: String? = null,
@Json(name="hotelName")
val hotelName: String? = null
)