簡體   English   中英

Gson反序列化 - 嘗試將JSON解析為Object

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

我試圖將JSON解析為Object。 有兩個類:User和Profile。 用戶獲得了個人資料的實例。

所以現在有一個JSON來構建用戶對象。 在這個JSON中是列出的User和Profile的屬性,正如你所看到的,Profile和User都得到了一個名為List的HashMap。 但是,我想從這個Json創建用戶和配置文件,但我有這個例外:

//編輯:

我從Profile和User中刪除了Map<String, String> links 所以現在我沒有得到任何錯誤,每個用戶都有一個配置文件 - 但我仍然需要這些地圖。 是否有可能GSON無法區分json中的兩個列表資源,因為它們具有相同的名稱?

// Dirty Hack解決方案: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反序列化器類。 它們很簡單:

要使其工作,您必須確保解析器不會嘗試序列化侵權對象(在本例中為您的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.
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM