Gson反序列化 - 试图将JSON解析为对象 [英] Gson deserialization - Trying to parse a JSON to an Object

查看:83
本文介绍了Gson反序列化 - 试图将JSON解析为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个JSON解析为一个Object。有两个类:用户和配置文件。用户得到了Profile的一个实例。



现在有了一个JSON来构建用户对象。在此JSON内部列出了用户和配置文件的属性,您可以看到,配置文件和用户都获得了名为List的HashMap。然而,我想创建用户和配置文件出这个JSON,但我得到这个例外:



//编辑:



我删除了 Map< String,String>链接来自Profile和User。所以现在我没有得到任何错误,每个用户都有一个档案 - 但我仍然需要这些地图。 GSON不能区分json中的两个列表资源,因为它们具有相同的名称吗?



//脏乱的解决方案:
ArrayList而不是HashMap是没有问题的。然而,我决定解析JSON的这部分手动插入对象到我的HashMap ..

  01-03 05:27:59.580:E / AndroidRuntime(4313):com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预计BEGIN_ARRAY,但是BEGIN_OBJECT在第1行12 
01-03 05:27:59.580: E / AndroidRuntime(4313):在com.google.gson.internal.bind.ReflectiveTypeAdapterFactory $ Adapter.read(ReflectiveTypeAdapterFactory.java:180)

User:

  public class User {
private String username;
私有字符串slu;;
私人字符串电子邮件;
私有布尔值emailVerified;
私人档案资料;
Map< String,String>链接;
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;


$ / code $ / pre
$ b pre

  public class Profile {

私人地图< String,String>链接;
私人字符串名称;
私有字符串描述;
私人字符串性别;
私人字符串状态;
私人字符串时区;
私人位图图标;

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,
:https://xxx.com/rels/collection/follower
},
{ href:http://xxx.de/api/users/4f3a73004bb67751bc000011/friends,
:https://xxx.com/rels/collection/friend
},
{href:http://xxx.de/api/users/4f3a73004bb67751bc000011/activity_stream,
rel:https://xxx.com/rels/activity_stream
$ bprofile:{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
}
],
名称:Foo Bar,
status:状态,
时区:CET
},
slug:foobaar,
username:foobaar
}

访问方式:

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

尝试{
jsonObject = new JSONObject(json);
Log.v(TAG,jsonObject.toString(2));
User u = gson.fromJson(jsonObject.toString(),User.class);
返回你;

} catch(JSONException e){
Log.e(TAG,解析JSON(USER)时发生错误+ e);
}
返回null;
}

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

解决方案

使用Gson Deserializer类。它们非常简单:为了实现这个功能,你必须确保解析器不会尝试序列化侵权对象
(在这个例子中案例你的地图)。我会将你的地图对象重命名为_links或some,这样序列化程序将跳过它。和你的配置文件中的这个例子一样。



一旦你完成了,你必须反序列化它,并确保将反序列化器包含在gson对象中:

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


public class UserDeserializer实现了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);
//遍历je元素来填充你的地图。
}

}


I am trying to parse a JSON into an Object. There are two classes: User and Profile. User got an instance of Profile.

So now there is one JSON to build an User Object. 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. However i'd like to create the User and the Profile out of this Json, but i got this Exception:

//EDIT:

I removed the Map<String, String> links from Profile and User. 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?

//Dirty Hack Solution: An ArrayList instead of the HashMap was no problem. However I decided to parse this part of the Json "by hand" to insert the Objects into my 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:

{ "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? Thanks in advance

解决方案

Use a Gson Deserializer class. 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). I would rename your map object to _links or somesuch so the serializer will skip over it. 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:

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

}

这篇关于Gson反序列化 - 试图将JSON解析为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆