GSON投掷“预期BEGIN_OBJECT但是BEGIN_ARRAY”

时间:2013-11-29 11:59:55

标签: android json gson

我的课程:

public class MyClass { 

    public HashMap<Integer, HashMap<String, PointFMP[] >> matchingPages;

    public static class PointFMP{
        public float x;
        public float y;
    }
}

我的杰森:

{
    "matchingPages": {
        "1": {
            "Butter": [
                {
                    "x": 16.23,
                    "y": 21.11
                },
                {
                    "x": 18.18,
                    "y": 26.67
                }
            ],
            "Cake": [
                {
                    "x": 13.23,
                    "y": 21.11
                }
            ]
        },
        "2": {
            "Other value": [
                {
                    "x": 41.98,
                    "y": 47.62
                }
            ]
        }
    }
}

解析:

Gson gson = new GsonBuilder().create();
MyClass response = gson.fromJson(jsonString, MyClass.class);

我的错误:

  

11-29 12:56:47.017:W / System.err(8169):   com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:   预计BEGIN_OBJECT但在STRING第1栏第1至11栏   12:56:47.022:W / System.err(8169):at   com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:176)

知道如何正确解析它吗?

2 个答案:

答案 0 :(得分:0)

您的输入无效Json。它应该是这样的:

{
    "1": {
         "Butter": [
         {
            "x": 16.23,
            "y": 21.11
        },
        {
            "x": 18.18,
            "y": 26.67
        }
        ]
    },
    "2": {
        "Butter": [
        {
            "x": 41.98,
            "y": 47.62
        }
        ]
    }
}

答案 1 :(得分:0)

你的json格式是正确的,你可以解析它如下

   public class PointFMP {

    @SerializedName(value="Butter")
    List<Butter> butter;

    @Override
    public String toString() {
        return "PointFMP [butter=" + butter + "]";
    }
}


public class Butter {

    public double x;
    public double y;
    @Override
    public String toString() {
        return "PointFMP [x=" + x + ", y=" + y + "]";
    }
}

Gson gson = new Gson();
Map<String, PointFMP> categoryMap  =
 gson.fromJson(reader, new TypeToken<Map<String, Map<String, PointFMP >>>(){}.getType());

结果如下

{1=PointFMP [butter=[PointFMP [x=16.23, y=21.11], PointFMP [x=18.18, y=26.67]]], 2=PointFMP [butter=[PointFMP [x=41.98, y=47.62]]]}
相关问题