Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson Expected STRING but was BEGIN_ARRAY?

Tags:

java

json

gson

I'm trying to parse a JSON string like this one ( the Json string is obtained from an online API)

[
 [
  [
   {
    "id": 0, 
    "number": 22,
    "arg": []
   }, 
   {
    "id": 1, 
    "number": 1, 
    "arg": [
     {
      "id": 0, 
      "type": "A0", 
      "beg": 0, 
     }, 
     {
      "id": 1, 
      "type": "A1", 
      "beg": 2, 
     }
    ]
   }   
  ]
 ]
]

I am using Gson library for java. My work is to get the value of the "number" attribute. To do that, I think I need to do:

jsonobject = something(???)
number = jsonobject[0][0][1]["number"]

So I try:

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(jstring).getAsJsonArray();
for(JsonElement obj : jArray )
{

String cse = gson.fromJson( obj , String.class);
System.out.println(cse);
}

however, java complains: Expected STRING but was BEGIN_ARRAY, from this line:

String cse = gson.fromJson( obj , String.class);

any thought? thanks in advance.

like image 982
Student Jack Avatar asked Mar 20 '23 06:03

Student Jack


1 Answers

It return ArrayList<ArrayList<ArrayList<Map<String, Object>>>>.

Type type = new TypeToken<ArrayList<ArrayList<ArrayList<Map<String, Object>>>>>() {}.getType();
ArrayList<ArrayList<ArrayList<Map<String, Object>>>> data = gson.fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

Or you can convert in into JAVA object as well

class MyJSONObj{
    private double id;
    private double number;
    private List<MyArgJson> arg;
    // getter & setter
}

class MyArgJson{
    private double id;
    private String type;
    private double beg;
    // getter & setter
}

Type type = new TypeToken<ArrayList<ArrayList<ArrayList<MyJSONObj>>>>() {}.getType();
ArrayList<ArrayList<ArrayList<MyJSONObj>>> data = gson.fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

output:

[
  [
    [
      {
        "id": 0.0,
        "number": 22.0,
        "arg": []
      },
      {
        "id": 1.0,
        "number": 1.0,
        "arg": [
          {
            "id": 0.0,
            "type": "A0",
            "beg": 0.0
          },
          {
            "id": 1.0,
            "type": "A1",
            "beg": 2.0
          }
        ]
      }
    ]
  ]
]
like image 72
Braj Avatar answered Apr 27 '23 08:04

Braj