【问题标题】:How to parse get roles value from this json?如何解析从此json获取角色值?
【发布时间】:2018-02-13 06:49:21
【问题描述】:

这是 json 响应。

{
  "roles": [
    "merchant"
  ]
}

我正在使用改造和 gson。如何获得角色的价值?目前我收到此错误“java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY”

【问题讨论】:

标签: android gson retrofit2


【解决方案1】:

你的 pojo 类应该是这样的。然后它会起作用

public class MyPojo
 {
private String[] roles;

public String[] getRoles ()
{
    return roles;
}

public void setRoles (String[] roles)
{
    this.roles = roles;
}

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

【讨论】:

  • 感谢您的帮助。我使用你的代码,它可以工作。再次感谢。
【解决方案2】:

如果你有一个想法,每次角色都是JsonArray,那么你可以直接在你的pojo类中使用Arraylist,但是如果角色不知道是JsonObject还是JsonArray,那么你必须在你的Pojo中使用它作为JsonElement喜欢:

private JsonElement roles;

public JsonElement getRoles (){
    return roles;
}

public void setRoles (JsonElement roles){
    this.roles = roles;
}

创建 pojo 后,您可以通过使用

检查 jsonelement 是 Object 还是 Array 的实例来转换 jsonelement
if(roles instanceof JsonObject)

然后相应地使用 Gson 进行转换。

编码愉快!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-20
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多