Gson用数组解析Json [英] Gson parse Json with array

查看:238
本文介绍了Gson用数组解析Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构建一个能解析出gson的类的时候遇到了一些麻烦,因为我希望这样做。



我创建了一个类。

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

并称为

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

以下是我的json

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

我已经成功地使用过gson,但从来没有像这样的数组。我应该不使用List / ArrayList吗?



我收到错误讯息;

 线程main中的异常com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:未终止的对象在第1行第31列

OpenCSV代码

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


解决方案

这里的问题是您有您的JSON中的浮点数字数组的数组。你的类应该是

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

解析上述内容并尝试

  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))); b



$ b $ p code> 1
2
[-66.9,18.05]


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],......);

解决方案

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]

这篇关于Gson用数组解析Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆