Android:将JSON对象值转换为指定的类

时间:2014-02-26 13:10:35

标签: java android json

我是Android开发和JAVA的新手。我需要将JSONObject值传递给android类。我知道像GSON这样的外部库(比如Jackson),但是对于这个任务,我只使用JSON。到目前为止,我已经创建了一个JSONObject:

public void jsonObject(){

    JSONObject test1 = new JSONObject();
    try{
        test1.put("name", "Pete");
        test1.put("surname", "Thompson");
        test1.put("age", "24");
        test1.put("height","182");
        test1.put("id", "45");
    }
    catch (JSONException a){
        a.printStackTrace();
    }
}

从这个对象,我需要将数据传递给以下类成员:

private String name;
private String surname;
private int age;
private int height;
private long id;

提前致谢。

4 个答案:

答案 0 :(得分:3)

然后为你的班级制作合适的构造函数:

public class Test {
    String name;
    String surname;
    int age;
    int height;
    long id;

    public Test(JSONObject jsonObject) {
        this.name = jsonObject.getString("name");
        this.surname = jsonObject.getString("surname");
        this.age = jsonObject.getInt("age");
        this.height = jsonObject.getInt("height");
        this.id = jsonObject.getLong("id");
    }
}

答案 1 :(得分:1)

try{    
    String name = test1.getString("name");
    String surName= test1.getString("surname");
    int age = test1.getInt("age");
    int height = test1.getInt("height");
    long id = test1.getLong("id");
    YourClass mInstance = new YourClass(name,surName,age,height,id);
}
catch(JSONParseException){
}

答案 2 :(得分:1)

使用GSON时的工作量如下所示:

使用GSON生成的对象:

class MyUser{

    @Expose @SerializedName("name");
    private String name;

    @Expose @SerializedName("surname");
    private String surname;

    //and so on

    public String getName(){
        return name;
    }

    public static MyUser fromJson(String json){
        return new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
                    .create().fromJson(json, MyUser.class);
    }

}

使用方法:

class WorkWithObjects{
    private MyUser currentUser;

    public void dataRecieved(String json){
        currentUser = MyUser.fromJson(json);
        Log.i("NAME", "IS " + currentUser.getName());
    }

}

答案 3 :(得分:0)

private String name;
private String surname;
private int age;
private int height;
private long id;

public JSONObject writeJsonObject(){

    JSONObject obj = new JSONObject();
    try{
        obj.put("name", name);
        obj.put("surname", surname);
        obj.put("age", age);
        obj.put("height",height);
        obj.put("id", id);
    }
    catch (JSONException a){
        a.printStackTrace();
    }
    return obj ;
}
public Test(JSONObject obj) {
    this.name = obj.getString("name");
    this.surname = obj.getString("surname");
    this.age = obj.getInt("age");
    this.height = obj.getInt("height");
    this.id = obj.getLong("id");
}