我有一个JSON数组数组,其中没有任何元素被命名(它只是一个纯数组)
[
["http://test.com/","rj76-22dk"],
["http://othertest.com/","v287-28n3"]
]
在Java中,我想将这个JSON解析为一个connectionobjs数组,其中connectionobj类如下所示:
public static class connectionOptions {
String URL, RESID;
}
我查看了GSON文档,但似乎找不到任何与将JSON数组解析为除另一个Java数组之外的任何内容相关的内容。我想将JSON数组解析为Java对象,而不是数组。
有没有办法使用谷歌的GSON?
答案 0 :(得分:1)
我根本不推荐这个。您应该尝试使用适当的JSON正确映射到Pojos。
如果您无法更改JSON格式,则需要注册可以进行转换的自定义TypeAdapter
。像
class ConnectionOptionsTypeAdapter extends TypeAdapter<ConnectionOptions> {
@Override
public void write(JsonWriter out, ConnectionOptions value)
throws IOException {
// implement if you need it
}
@Override
public ConnectionOptions read(JsonReader in) throws IOException {
final ConnectionOptions connectionOptions = new ConnectionOptions();
in.beginArray();
connectionOptions.URL = in.nextString();
connectionOptions.RESID = in.nextString();
in.endArray();
return connectionOptions;
}
}
然后只需注册
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(
ConnectionOptions.class, new ConnectionOptionsTypeAdapter());
Gson gson = gsonBuilder.create();
并使用它。
将您的JSON反序列化为ConnectionOptions[]
或List<ConnectionOptions>
。
我已将您的类名更改为ConnectionOptions
以遵循Java命名约定。
答案 1 :(得分:1)
您应该提供自定义的反序列化器。
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
public class TestGson {
public static class ConnectionOptions {
String URL, RESID;
@Override
public String toString() {
return "ConnectionOptions{URL='" + URL + "', RESID='" + RESID + "'}";
}
}
private static class ConnOptsDeserializer implements JsonDeserializer<ConnectionOptions> {
@Override
public ConnectionOptions deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ConnectionOptions connOpts = new TestGson.ConnectionOptions();
JsonArray array = json.getAsJsonArray();
connOpts.URL = array.get(0).getAsString();
connOpts.RESID = array.get(1).getAsString();
return connOpts;
}
}
public static void main(String[] args) {
String json = "[[\"http://test.com/\",\"rj76-22dk\"],\n" +
" [\"http://othertest.com/\",\"v287-28n3\"]]";
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(ConnectionOptions.class, new ConnOptsDeserializer());
Gson gson = gsonb.create();
Type collectionType = new TypeToken<Collection<ConnectionOptions>>(){}.getType();
Collection<ConnectionOptions> connList = gson.fromJson(json, collectionType);
System.out.println("connList = " + connList);
}
}