Gson parse Json with array

隐身守侯 提交于 2019-12-31 03:12:09

问题


I am having some trouble building a class which will parse out gson as I expect it to.

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

  {
   "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. Should I not be using the 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

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

回答1:


The problem here is that you have an array of arrays of arrays of floating point numbers in your 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]


来源:https://stackoverflow.com/questions/18880066/gson-parse-json-with-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!