java - Gson 反序列化 - 尝试将 JSON 解析为对象

标签 java android json serialization gson

我正在尝试将 JSON 解析为对象。有两个类:用户和配置文件。用户获得了 Profile 的实例。

所以现在有一个 JSON 来构建用户对象。在这个 JSON 中列出了 User 和 Profile 的属性,如您所见,Profile 和 User 都有一个名为 List 的 HashMap。但是我想从这个 Json 中创建用户和配置文件,但是我得到了这个异常:

//编辑:

我删除了 Map<String, String> links来自配置文件和用户。所以现在我没有收到任何错误,每个用户都有一个配置文件 - 但我仍然需要那些 map 。 GSON 是否可能无法区分 json 中的两个列表资源,因为它们具有相同的名称?

//肮脏的黑客解决方案: ArrayList 而不是 HashMap 是没有问题的。但是,我决定“手动”解析 Json 的这一部分,以将对象插入到我的 HashMap 中。

01-03 05:27:59.580: E/AndroidRuntime(4313): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 12
01-03 05:27:59.580: E/AndroidRuntime(4313):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:180)

用户:

public class User {
    private String username;
    private String slug;
    private String email;
    private Boolean emailVerified;
    private Profile profile;
    Map<String, String> links;
    public User()
    {
        this.username = null;
        this.slug = null;
        this.email = null;
        this.emailVerified = null;
        this.profile = null;
        this.links = new HashMap<String, String>();
    }

    public String getUsername(){
        return this.username;
    }

    public String getSlug(){
        return this.slug;
    }

    public String getEmail(){
        return this.email;
    }

    public Boolean getEmailVerified(){
        return this.emailVerified;
    }

    public Profile getProfile(){
        return this.profile;
    }
}

简介:

public class Profile {

    private Map<String, String> links;
    private String name;
    private String description;
    private String gender;
    private String status;
    private String timezone;
    private Bitmap icon;

    public Profile()
    {
        this.name = null;
        this.description = null;
        this.gender = null;
        this.status = null;
        this.timezone = null;
        this.links = new HashMap<String, String>();
    }

    public String getName(){
        return this.name;
    }

    public String getDescription(){
        return this.description;
    }

    public String getGender(){
        return this.gender;
    }

    public String getStatus(){
        return this.status;
    }

    public String getTimezone(){
        return this.timezone;
    }
}

JSON 示例:

{ "email" : "foo@bar.com",
  "emailVerified" : true,
  "links" : [ { "href" : "http://xxx.de/api/users/4f3a73004bb67751bc000011",
        "rel" : "self"
      },
      { "href" : "http://xxx.de:/api/users/4f3a73004bb67751bc000011/followers",
        "rel" : "https://xxx.com/rels/collection/follower"
      },
      { "href" : "http://xxx.de/api/users/4f3a73004bb67751bc000011/friends",
        "rel" : "https://xxx.com/rels/collection/friend"
      },
      { "href" : "http://xxx.de/api/users/4f3a73004bb67751bc000011/activity_stream",
        "rel" : "https://xxx.com/rels/activity_stream"
      }
    ],
  "profile" : { "description" : "",
      "gender" : "male",
      "links" : [ { "href" : "xxx.de/uploads/profile_images/xxx.png",
            "rel" : "https://xxx.com/rels/image"
          },
          { "href" : "http://xxx.de/api/users/xxx/profile",
            "rel" : "self"
          }
        ],
      "name" : "Foo Bar",
      "status" : "Status",
      "timezone" : "CET"
    },
  "slug" : "foobaar",
  "username" : "foobaar"
}

访问方法:

public static User parseUser(String json) {
        JSONObject jsonObject;
        Gson gson = new Gson();

        try {
            jsonObject = new JSONObject(json);
            Log.v(TAG,jsonObject.toString(2));
            User u = gson.fromJson(jsonObject.toString(), User.class);
            return u;

        } catch (JSONException e){
            Log.e(TAG, "There was an error parsing the JSON (USER)" + e);
        }
        return null;
    }

我的错误在哪里?我可以在 GSON 中使用这样的 HashMap 吗?提前致谢

最佳答案

使用 Gson Deserializer 类。它们非常简单:

要使其正常工作,您必须确保解析器不会尝试序列化侵权对象 (在这种情况下是您的 map )。我会将您的 map 对象重命名为 _links 或类似的名称,以便序列化程序将跳过它。对您的个人资料也执行与此示例相同的操作。

完成后,您必须对其进行反序列化,并确保在 gson 对象中包含反序列化器:

    User u;
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(User.class, new UserDeserializer());
    Gson g = gb.create();
    u = g.fromJson(json, User.class);


public class UserDeserializer  implements JsonDeserializer<UserDeserializer>
{
   @Override
   public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    {
        User u = g.fromJson(json, User.class);
        JsonObject jo = (JsonObject)json;
        JsonElement je = jo.get("links");
        //iterate through the je element to fill your map.
    }

}

关于java - Gson 反序列化 - 尝试将 JSON 解析为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9296427/

相关文章:

java - 亚马逊 MWS listMatchingProducts 超过 10 个结果?

java - 如何在android studio项目中包含共享库?

java - Google Map Android API V2 中两个位置之间的行驶距离和旅行持续时间

java - MapView 上的空指针异常

java - 如何关闭另一个类的 Intent Activity

javascript - Fabric js loadFromJSON 问题

python - 从嵌套字典/json 中删除键

java - 使用 Retrofit 从最内部类获取数据。帮我显示A类和B类的数据

java - 读取文件并添加额外的 "\"

Android ValueAnimator 正弦波