【问题标题】:How to deserialize a keyless array with GSON?如何使用 GSON 反序列化无密钥数组?
【发布时间】:2012-06-24 10:45:56
【问题描述】:

我喜欢使用GSON 来反序列化下面的 JSON 字符串。

{
  "type": "FeatureCollection",
  "features": [
    {
      "id": "FSROGD.4440181",
      "geometry": {
        "type": "Point",
        "coordinates": [
          16.7594706041998,
          43.148716514354945
        ]
      }
    }
  ]
}

我已经准备好名为 ResponseFeaturesGeometryCoordinates 的必要 Java 类。除了最后一节课,一切都很好。但是对于坐标,我不明白我应该写什么,因为没有可以准备作为成员变量的键。
这是父 Geometry 类...

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;
}

... 和空的 Coordinates 类。

package info.metadude.trees.model.vienna;    
public class Coordinates {
    // TODO: No idea what should be defined here.
}

【问题讨论】:

  • 我认为坐标本身不应该是一个类,而只是几何类中的一个双精度数组。或者您必须提供自己的序列化器和反序列化器。

标签: java arrays json deserialization gson


【解决方案1】:

您可以将coordinates 用作Geometry 中的集合属性。这会自动将值映射到正确的属性。

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 + "]";
        }

    }

}

【讨论】:

  • 我会选择 Double,因为 Float 会缩短值。另外,据我了解,如果我的成员是公开的(我在 Android 环境中使用它),我不需要添加 getter 和 setter。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 2015-02-24
  • 2011-03-28
  • 2013-02-01
  • 1970-01-01
相关资源
最近更新 更多