简体   繁体   English

Gson反序列化 - 尝试将JSON解析为Object

[英]Gson deserialization - Trying to parse a JSON to an Object

I am trying to parse a JSON into an Object. 我试图将JSON解析为Object。 There are two classes: User and Profile. 有两个类:User和Profile。 User got an instance of Profile. 用户获得了个人资料的实例。

So now there is one JSON to build an User Object. 所以现在有一个JSON来构建用户对象。 Inside this JSON are the attributes for the User and Profile listed and as you can see, Profile and User got both a HashMap called List. 在这个JSON中是列出的User和Profile的属性,正如你所看到的,Profile和User都得到了一个名为List的HashMap。 However i'd like to create the User and the Profile out of this Json, but i got this Exception: 但是,我想从这个Json创建用户和配置文件,但我有这个例外:

//EDIT: //编辑:

I removed the Map<String, String> links from Profile and User. 我从Profile和User中删除了Map<String, String> links So now I do not get any errors and every User got a Profile - but I still need those Maps. 所以现在我没有得到任何错误,每个用户都有一个配置文件 - 但我仍然需要这些地图。 Is it possible that GSON cant differentiate between the two lists ressources inside of the json because they have the same name? 是否有可能GSON无法区分json中的两个列表资源,因为它们具有相同的名称?

//Dirty Hack Solution: An ArrayList instead of the HashMap was no problem. // Dirty Hack解决方案:ArrayList而不是HashMap没问题。 However I decided to parse this part of the Json "by hand" to insert the Objects into my 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)

User: 用户:

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;
    }
}

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;
    }
}

An example JSON: 一个示例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"
}

Accessing Method: 访问方法:

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;
    }

Where is my mistake? 我的错误在哪里? And can i use a HashMap like this with GSON? 我可以使用GSON这样的HashMap吗? Thanks in advance 提前致谢

Use a Gson Deserializer class. 使用Gson反序列化器类。 they are pretty straightforward: 它们很简单:

To make this work, you have to make sure the parser isn't going to try and serialize the infringing object (in this case your Map). 要使其工作,您必须确保解析器不会尝试序列化侵权对象(在本例中为您的Map)。 I would rename your map object to _links or somesuch so the serializer will skip over it. 我会将你的地图对象重命名为_links或者某些东西,所以序列化程序会跳过它。 Do the same thing as this example for your Profile as well. 对于您的个人资料,请执行与此示例相同的操作。

Once you've done that you have to deserialize it and make sure to include the deserializer in the gson object: 完成后,必须对其进行反序列化,并确保在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.
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM