簡體   English   中英

Android和json使用REST服務中的gson和嵌套對象

[英]Android and json using gson from REST service with nested objects

我的REST服務Android應用程序遇到問題。

我從服務器收到以下json響應:

{
"0": {
    "id": 1,
    "name": "Some Guy",
    "email": "example1@example.com"
},
"1": {
    "id": 2,
    "name": "Person Face",
    "email": "example2@example.com"
},
"3": {
    "id": 3,
    "name": "Scotty",
    "email": "example3@example.com",
    "fact": {
        "hobbies": ["fartings", "bikes"]
    }
}
}

我的對象是:

用戶類別:

public class User {
@SerializedName("id")
private
int id;

@SerializedName("name")
private
String name;

@SerializedName("email")
private
String email;

@SerializedName("fact")
private
Fact fact;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Fact getFact() {
    return fact;
}

public void setFact(Fact fact) {
    this.fact = fact;
}

public User(){}
}

事實類:

public class Fact {
@SerializedName("hobbies")
private List<Hobbies> hobbies;

public List<Hobbies> getHobbies() {
    return hobbies;
}

public void setHobbies(List<Hobbies> hobbies) {
    this.hobbies = hobbies;
}

public Fact(){}
}

興趣班:

public class Hobbies {
private String hobby;

public String getHobby() {
    return hobby;
}

public void setHobby(String hobby) {
    this.hobby = hobby;
}

public Hobbies(){}
}

當我在應用程序中使用以下代碼時:

private User jsonToUser(String result){
  User users = null;
  if(result != null && result.length() > 0){
    Gson gson = new GsonBuilder().create();
    users = gson.fromJson(result, User.class);
  }
return users;
}

函數返回的對象由空值填充。 我試圖使用類Users是空的並擴展ArrayList

public class Users extends ArrayList<User> {
//
}

和應用程序給我錯誤:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

我希望將其用於:

ArrayAdapter<User> adapter = new ArrayAdapter<User>(activity, android.R.layout.simple_list_item_1, users);

你能告訴我我在做什么錯嗎? 它適用於我的Twitter時間軸應用程序,但並不為此感到煩惱。

您的代碼users = gson.fromJson(result, User.class); 如果您想要將JSON字符串(例如{ "id": 1, "name": "Some Guy", "email": "example1@example.com" }轉換為一個 User對象,則可以使用。

但是像您這樣的JSON字符串

{
    "0": {
        "id": 1,
        "name": "Some Guy",
        "email": "example1@example.com"
    },
    ...
}

被解釋為User對象的數組(或HashMap ?!)

使用數組嘗試以下操作:

users = gson.fromJson(result, User[].class);

或(如果GSON將其解釋為HashMap ):

users = gson.fromJson(result, HashMap<String, User>.class);

使用Gson用戶指南中Collections示例代碼的更優雅的方式是使用Collection:

Type collectionType = new TypeToken<Collection<User>>(){}.getType();
Collection<User> users= gson.fromJson(result, collectionType);

在“收款限制”部分中,內容如下:

反序列化時,Collection必須是特定的通用類型

我不確定,但這可能意味着您必須將collectionType設置為使用List而不是Collection作為特定類型。

(如果GSON將其解釋為HashMap ):

Type hashMapType = new TypeToken<HashMap<String, User>>(){}.getType();
HashMap<String, User> users= gson.fromJson(result, hashMapType);

祝你好運=)

編輯

我對最后一個解決方案的嘗試是成功的:

public class User {
    private String id, name, email;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

public static void main(String[] args) {
    String result = ""
            + "{\"0\": {    \"id\": 1,    \"name\": \"Some Guy\",    \"email\": \"example1@example.com\"},"
            + "\"1\": {    \"id\": 2,    \"name\": \"Person Face\",    \"email\": \"example2@example.com\"}"
            + "}";

    Gson gson = new Gson();

    Type hashMapType = new TypeToken<HashMap<String, User>>() {
    }.getType();
    HashMap<String, User> users = gson.fromJson(result, hashMapType);
    for (String key : users.keySet()) {
        printUser(users.get(key));
    }
}

private static void printUser(User user) {
    System.out.printf("%s %s %s\n", user.getId(), user.getName(),
            user.getEmail());
}

暫無
暫無

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

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