1

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.

1 Answer 1

3

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}]'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.