RandomUser
RandomUser

Reputation: 4220

Java gson error: Expected BEGIN_OBJECT but was BEGIN_ARRAY (but my type map is correct?)

I am getting a gson exception: Expected BEGIN_OBJECT but was BEGIN_ARRAY. However, I'm not clear as to why as I've represented the structure correct.

My data:

[
    {
        "aws.amazon.com": 426788
    },
    {
        "atsv2-fp.wg1.b.yahoo.com": 141154
    },
    {
        "e2svi.x.incapdns.net": 140445
    },
    {
        "stackoverflow.com": 87624
    },
    {
        "a-sg03sl05.insnw.net": 56665
    }
]

My gson object:

public class GroupedTotals {
    public List<Map<String, Float>> BSRecvDestDNSName;
}

Usage:

Gson gson = new Gson();
GroupedTotals groupedTotals = gson.fromJson(output, GroupedTotals.class);

Exception:

Parse Error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

Any suggestions? If I change the code and json to be a map without the encapsulating array it works fine, but I need it to work with the array as I've written above.

Upvotes: 1

Views: 370

Answers (1)

azurefrog
azurefrog

Reputation: 10945

That's because GroupedTotals isn't a list, it is an object that contains a list.

Valid json that would convert into an instance of that class would look like

{
    "BSRecvDestDNSName": [
       ...
    ]
}

Alternately, you could obtain the Type for a list and convert directly to it. For instance, using your original json, this code:

Type type = new TypeToken<List<Map<String, Float>>>() {}.getType();
List<Map<String, Float>> myList = gson.fromJson(output, type);
System.out.println("myList='"+myList+"'");

Outputs

myList='[{aws.amazon.com=426788.0}, {atsv2-fp.wg1.b.yahoo.com=141154.0}, {e2svi.x.incapdns.net=140445.0}, {stackoverflow.com=87624.0}, {a-sg03sl05.insnw.net=56665.0}]'

Upvotes: 3

Related Questions