Java 如何使用GSON反序列化无键数组?
我喜欢使用反序列化以下JSON字符串Java 如何使用GSON反序列化无键数组?,java,arrays,json,deserialization,gson,Java,Arrays,Json,Deserialization,Gson,我喜欢使用反序列化以下JSON字符串 { "type": "FeatureCollection", "features": [ { "id": "FSROGD.4440181", "geometry": { "type": "Point", "coordinates": [ 16.7594706041998, 43.148716514354945 ] }
{
"type": "FeatureCollection",
"features": [
{
"id": "FSROGD.4440181",
"geometry": {
"type": "Point",
"coordinates": [
16.7594706041998,
43.148716514354945
]
}
}
]
}
我已经准备了必要的Java类,名为Response、Features、Geometry和Coordination。除了最后一节课,一切都很好。但是对于坐标,我不明白我应该写什么,因为没有可以作为成员变量准备的键。下面是父几何体类
package info.metadude.trees.model.vienna;
import com.google.gson.annotations.SerializedName;
public class Geometry {
@SerializedName("type")
public String type;
// TODO: Prepare Coordinates class for GSON.
// @SerializedName("coordinates")
// public Coordinates coordinates;
}
。。。和空坐标类
您可以使用
坐标
作为几何图形
中的集合属性。这将自动将值映射到正确的属性
import java.util.List;
import com.google.gson.Gson;
public class GSonTest {
public static void main(final String[] args) {
Gson gson = new Gson();
System.out.println(gson.fromJson("{ \"type\": \"Point\", \"coordinates\": [ 16.7594706041998, 43.148716514354945 ] }", Geometry.class));
}
public static class Geometry {
List<Float> coordinates;
public List<Float> getCoordinates() {
return coordinates;
}
public void setCoordinates(final List<Float> coordinates) {
this.coordinates = coordinates;
}
@Override
public String toString() {
return "Geometry [coordinates=" + coordinates + "]";
}
}
}
import java.util.List;
导入com.google.gson.gson;
公共类GSonTest{
公共静态void main(最终字符串[]args){
Gson Gson=新的Gson();
System.out.println(gson.fromJson(“{”type\“:\“Point\”,“coordinates\”:[16.7594706041998,43.1487165143549445]),Geometry.class));
}
公共静态类几何{
列出坐标;
公共列表getCoordinates(){
返回坐标;
}
公共无效集合坐标(最终列表坐标){
这个。坐标=坐标;
}
@凌驾
公共字符串toString(){
返回“几何体[坐标=”+坐标+“]”;
}
}
}
我认为坐标本身不应该是一个类,而是几何类中的一个双精度数组。或者您必须提供自己的序列化程序和反序列化程序。我会选择Double,因为Float缩短了值。另外,据我所知,如果我的成员是公共的,我不需要添加getter和setter(我在Android环境中使用它)。
import java.util.List;
import com.google.gson.Gson;
public class GSonTest {
public static void main(final String[] args) {
Gson gson = new Gson();
System.out.println(gson.fromJson("{ \"type\": \"Point\", \"coordinates\": [ 16.7594706041998, 43.148716514354945 ] }", Geometry.class));
}
public static class Geometry {
List<Float> coordinates;
public List<Float> getCoordinates() {
return coordinates;
}
public void setCoordinates(final List<Float> coordinates) {
this.coordinates = coordinates;
}
@Override
public String toString() {
return "Geometry [coordinates=" + coordinates + "]";
}
}
}