如何在没有名称和动态的情况下反序列化json对象?

时间:2017-10-12 16:03:37

标签: java android json gson pojo

我有这个JSON:

modelBuilder.Entity<Author>()
    .HasOne(e => e.Address)
    .WithOne()
    .HasForeignKey<Address>("AuthorId")
    .OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Publisher>()
    .HasOne(e => e.Address)
    .WithOne()
    .HasForeignKey<Address>("PublisherId")
    .OnDelete(DeleteBehavior.Cascade);

属性的名称将是动态的,也是JSON的长度。 我正在使用GSON工具,我创建了一个POJO,但没有名称,我无法引用它,这就是为什么我收到myError实例,为null。 这是我的POJO

{
    "username": [
        "A user with that username already exists."
    ],
    "ruc": [
        "user with this ruc already exists."
    ],
    "code": [
        "user with this code already exists."
    ],
    "document_number": [
        "user with this document number already exists."
    ]
}

这是我的GSON代码

public class MyError {
    public Map<String, Object> message = new HashMap<>();
}

我想为每个项目显示一条消息:

myError = new Gson().fromJson(response.errorBody().string(), MyError.class);

3 个答案:

答案 0 :(得分:1)

你可以尝试使用它:

Map myError = new Gson().fromJson(s, Map.class);

或者如果你想使用你的类,json应该如下:

{ "message": { "username": [ "A user with that username already exists." ], "ruc": [ "user with this ruc already exists." ], "code": [ "user with this code already exists." ], "document_number": [ "user with this document number already exists." ] } }

答案 1 :(得分:0)

几个月前我有一个类似的问题,发现这个答案非常有帮助:

How to parse dynamic JSON fields with GSON?

答案 2 :(得分:0)

考虑使用Gson和java原生JsonParser。