使用Gson将JSON对象解析为Map a JsonSyntaxException

toe95027  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(153)

我有一个Map属性:

private Map<String, Attribute> attributes = new HashMap<>();

Attribute对象如下所示:

public class Attribute{
     private String value;
     private String name;

//with constructor setters and getters
}

如何将Map对象的属性表示为JSON?
我得到一个JsonSyntaxException

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

在下面的代码中,当我尝试使用fromJson()转换JSON对象时:

Attribute attribute = Gson().fromJson(jsonObect,Attribute.class)

我的JSON对象如下所示:

{
   "attributes":[
      {
         "name":"some name",
         "value":"some value"
      }
   ]
}
ibps3vxo

ibps3vxo1#

很容易检查:

Map<String,Attribute> attributes = new HashMap<>();
    attributes.put("key_0", new Attribute("value_0", "name_0"));// I added constructor and getter/setter methods to class Attribute
    attributes.put("key_1", new Attribute("value_1", "name_1"));
    attributes.put("key_2", new Attribute("value_2", "name_2"));
    //serialize using ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    var s = mapper.writeValueAsString(attributes);
    System.out.println(s);

输出:

{
   "key_2":{
      "value":"value_2",
      "name":"name_2"
   },
   "key_1":{
      "value":"value_1",
      "name":"name_1"
   },
   "key_0":{
      "value":"value_0",
      "name":"name_0"
   }
}
siotufzp

siotufzp2#

我得到:"Expected BEGIN_ARRAY but was BEGIN_OBJECT"错误,当我试图在下面的代码中使用fromJson()转换JSON对象时:
Attribute attribute = Gson().fromJson(jsonObect,Attribute.class)
以下 *JSON对象 * 既不匹配单个Attribute对象,也不匹配MapMap<String, Attribute>

{
   "attributes":[
      {
         "name":"some name",
         "value":"some value"
      }
   ]
}

仔细看一下,Map到键"attributes"的值是 JSON-array
因此,您可以成功地将其解析为类型为Map<String, List<Attribute>>的Map
这就是如何使用Gson.fromJson()TypeToken实现它(* 有关更多选项,请参阅此question *):

public static void main(String[] args) {

    String jsonStr = """
        {
            "attributes":[
               {
                  "name":"some name",
                  "value":"some value"
               }
            ]
         }""";

    Gson gson = new Gson();

    Type mapStrByStr = new TypeToken<Map<String, List<Attribute>>>(){}.getType();
    Map<String, List<Attribute>> map = gson.fromJson(jsonStr, mapStrByStr);

    System.out.println(map);
    }
}

public static class Attribute{
    private String value;
    private String name;

    @Override
    public String toString() {
        return "Attribute{" +
            "value='" + value + '\'' +
            ", name='" + name + '\'' +
            '}';
    }
}
  • 输出:*
{attributes=[Attribute{value='some value', name='some name'}]}

相关问题