How to use fromGson with arrays

南楼画角 提交于 2019-12-13 04:06:29

问题


I have the json:

{"test": [{"param1": "param"}],
  "test2": "test",
 "test3": "test2"}

how can I get fromGson to parse the arrays in a json correctly so that it populates the arrays into an array of a particular object type.

So test should map to TestObject[] test;

test2 -> String test2;
test3 -> String test3;

I tried gson.fromJson(response, TestData.class); that gave me an error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 664

( that the fromJson is not parsing the array in the json correctly).

I also tried going through this post: Parsing JSON array into java.util.List with Gson

But got confused.

but that did not work


回答1:



Answer

public class TestClass {
    public String param1;   
}

public class TestMap {
    public TestClass[] Test;
    public String test2;
    public String test3;
}

public Collection<TestMap> collectionFromJSON(String jsonString) {
    Gson gson = new Gson();
    Collection<TestMap> testMaps = gson.fromJson(jsonString, new TypeToken<Collection<TestMap>>() {
    }.getType());
    return testMaps;
}

public TestMap singleFromJSON(String jsonString) {
    Gson gson = new Gson();
    Journal testMap = gson.fromJson(jsonString, TestMap.class);
    return testMap;
}

Okay, I will explain something here.


Explain

Normally if you have a nested array of objects inside another object, you need to create a new class. Ie. if Journal has Categories, Category has two other properties, title and index.

The class will be like

class Journal {
    public Category[] categories;
    .... 
}

class Category {
    public String title;
    public Integer index;
    .... 
}

So now, the mistake is to confused Array of String and Array of Class. If the json is

{"Test", ["Test1", "Test2"...]
 "Test2": "Test3"}

You can define it as an array of String. But it is a nested JSON Object, so it has to be class again.




回答2:


Without seeing your class, I'm going to guess. This error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 664

means you are trying to deserialize a String, so something like

"some string"

but what the JSON actually contained was a JSON object, something like

{"name" : "value"}

Your class is probably mapped wrong. It should be

String test2;
String test3;
TestObject[] test;

where TestObject should be

public class TestObject {
    String param1;
}

since the JSON contains an JSON string called param1.




回答3:


python has a very useful module called json

try var TestObject=json.parse()



来源:https://stackoverflow.com/questions/21322922/how-to-use-fromgson-with-arrays

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