java - GSON读入数组类元素

标签 java gson topojson

我想将 topojson 对象读入 Java 类。 Topojson 是一种特殊的 JSON 类,定义为对象在查找表中具有弧线的位置,如下所示:

{
  "type":"Topology",
  "objects":{
    "collection":{
      "type":"GeometryCollection",
      "geometries":[
        {"type":"LineString","properties":{"id":842296681,"start":892624561,"end":892624564,"class":5,"lanes":null,"direction":"B","length":0.000485},"arcs":[0]},
        {"type":"LineString","properties":{"id":842296682,"start":892624563,"end":892624564,"class":5,"lanes":null,"direction":"B","length":0.000351},"arcs":[1]},
      ]
    }
  },
  "arcs":[
    [[4816,1007],[262,2281],[183,738]],
    [[4397,3892],[341,-268],[235,0],[288,402]]
  ],
  "transform":{
    "scale":[3.8203658765624953e-7,1.4901510251040002e-7],
    "translate":[-87.63437999816,41.86725999012999]},
    "bbox":[-87.63437999816,41.86725999012999,-87.63056001432003,41.86874999213999]
}

我正在尝试按照 in this answer 的建议进行操作,并将对象直接读入一个类中,我将其定义为有点尴尬

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by gregmacfarlane on 7/11/17.
 */
public class TopoJsonNetwork {
  String type;
  Map<String, GeometryCollection> objects;
  ArrayList<Double[][]> arcs;
  Transform transform;

}

class GeometryCollection{
  String type;
  Geometry[] geometries;

}

class Geometry{

  String type;
  Map<String, String> properties;
  Integer[] arcs; // lines will have only a single arc


}


class Transform{
  Double[] scale;
  Double[] translate;
  Double[] bbox;

}

当我调用 gson 阅读器时一切正常

reader = new JsonReader(new FileReader(topoFile));

Gson gson = new Gson();
TopoJsonNetwork topoNet = gson.fromJson(reader, TopoJsonNetwork.class);

这意味着我的类的所有对象都已填充 --- 除了 arcs 数组。该元素存在,但具有 null 值。我应该如何更改此元素的定义方式才能正确填充?

最佳答案

使用您的代码我能够得到预期的结果。我修改了你的主程序,并使用嵌套 for 循环将 ArrayList 作为 2D 数组进行循环。结果是您类(class)中 arcs 列表中所有数字的列表。

JsonReader reader = new JsonReader(new FileReader("topojson.json"));
Gson gson = new Gson();
TopoJsonNetwork topoNet = gson.fromJson(reader, TopoJsonNetwork.class);

for (Double[][] d : topoNet.arcs) {
    for (int i = 0; i < d.length; i++) {
        for (int j = 0; j < d[i].length; j++) {
            System.out.println(d[i][j]);
        }
    }
}

在本例中,topoNet.arcs 是一个大小为 2 的列表,正如您所期望的,它包含几个二维 Double 数组。

关于java - GSON读入数组类元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046706/

相关文章:

int - Kotlin 数据类 Gson 序列化问题

javascript - 如何在 D3 TOPOJSON map 加载后运行函数

java - 查找 Java 字符串中出现的字符

java - 如何保存用户选择的 Intent ?

java - facebook api(java或php): how to request the user to add the application when he opens it?

java - 如何让 Android Volley 解析我对工作线程中 POJO 的 Json 响应

java - Hibernate - 如何仅在属性不为空时获取属性?

java - 如何使用 GSON 指定序列化?

javascript - 如何重绘D3 map 中的标签?

javascript - 在 D3 中使用投影进行动态简化