简体   繁体   English

Gson用数组解析Json

[英]Gson parse Json with array

I am having some trouble building a class which will parse out gson as I expect it to. 我在建立一个可以按预期解析gson的类时遇到了麻烦。

I created a class. 我创建了一个课程。

public class JsonObjectBreakDown {
    public String type; 
    public List<String> coordinates = new ArrayList<String>();
}

And called 并称为

JsonObjectBreakDown p = gson.fromJson(withDup, JsonObjectBreakDown.class);

Below is my json 以下是我的json

  {
   "type":"Polygon",
   "coordinates":[
      [
         [
            -66.9,
            18.05
         ],
         [
            -66.9,
            18.05
         ],
         [
            -66.9,
            18.06
         ],
         [
            -66.9,
            18.05
         ]
      ]
   ]
}

I have used gson before successfully, but never with an array like this. 我之前曾成功使用过gson,但从未将其用于这样的数组。 Should I not be using the List/ArrayList? 我应该不使用List / ArrayList吗?

I get the error message; 我收到错误消息;

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 31

OpenCSV code OpenCSV代码

CSVReader reader = new CSVReader(new FileReader("c:\\Json.csv"));
String tmp = reader.readNext();
CustomObject tmpObj = CustomObject(tmp[0], tmp[1],......);

The problem here is that you have an array of arrays of arrays of floating point numbers in your JSON. 这里的问题是,您的JSON中有一个浮点数数组的数组 Your class should be 你的课应该是

public class JsonObjectBreakDown {
    public String type; 
    public List<List<float[]>> coordinates = new ArrayList<>();
}

Parsing with the above and trying 解析以上并尝试

System.out.println(p.coordinates.size());
System.out.println(p.coordinates.get(0).size());
System.out.println(Arrays.toString(p.coordinates.get(0).get(0)));

yields 产量

1
2
[-66.9, 18.05]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM