无法使用gson解析json

时间:2014-07-22 11:47:07

标签: android json gson

任何人都可以帮助我使用gson库解析这个json。 我无法为这个Json

创建正确的POJO类
{"status":"ok","result":[{"name":"Al Mansoori Villa in Al Khawaneej","reference":"UB5647","link":"\/index.php?r=apiv1\/projects\/view&id=21570"},{"name":"Mr. Mohammad Dhanhani Villa in Dibba","reference":"UB6046","link":"\/index.php?r=apiv1\/projects\/view&id=22970"},{"name":"Villa in Al Barsha","reference":"UB6664","link":"\/index.php?r=apiv1\/projects\/view&id=25877"},{"name":"Bin Omeir Hospital in Abu Dhabi","reference":"UB6054","link":"\/index.php?r=apiv1\/projects\/view&id=23291"}]}

提前致谢

4 个答案:

答案 0 :(得分:2)

检查使用GSON解析JSON数组的this链接 这可能对你有帮助......

答案 1 :(得分:1)

我能够使用POJO解析此问题。您必须确保在Annotation样式下选择GSON并在Source type下:选择JSON。然后在你的代码中转换为

单个对象

/**
 * This will convert json string to User object.
 * @param jsonUserString
 * @return <b>User object/b>
 */
public User convertFromJsonStringToUserObject(String jsonUserString){
    Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    Type listType = new TypeToken<User>() {}.getType();
    return g.fromJson(jsonUserString, listType);
}//END 

对象的ArrayList。

/**
 * Convert string to {@link ArrayList} of {@link Address}
 * @param jsonAddress <b>String</b> json string
 * @return <b>{@link ArrayList} of {@link Address}</b>
 */
public ArrayList<Address> convertJsonStringToAddressObjectArray(String jsonAddress){
    ArrayList<Address> addressList = new ArrayList<Address>();
    Type listType = new TypeToken<List<Address>>() {}.getType();
    Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    addressList=g.fromJson(jsonAddress, listType);
    return addressList;
}//END

答案 2 :(得分:1)

根据您的回复,您需要有一个班级:

在您的情况下,如下所示:

public class MyResponse{
    public String status = "";
    public List<Result> result;
    public MyResponse{
        result = new ArrayList<MyResponse.Result>();
    }

    //getter setter for status and result

    public class Result{
        public String name="";
        public String reference="";
        public String link="";
        public Result(){

        }
        //getter setter for name, reference, link
    }

}

然后将其解析为:

MyResponse response = new Gson().fromJson(responseString,
                    MyResponse.class);

希望这有帮助。

答案 3 :(得分:1)

响应似乎很简单,其状态为String,数组列表为&#34;结果&#34;(s)

要直接使用Gson,您可以使用Result数组对象的独立类以相同的方式设置模型类。

应该使用:

class JsonResponseModel{

String status;

@SerializedName("result") //optional to use, you can name the variable as "result"
ArrayList<ResultInResponse> resultArrayList;

//getters setters
//toString for the class, works well to verify data populated
}

现在是结果类

class ResultInResponse{

String name;

String reference;

String link;

//getters setters
//toString for the class
}

实现:

Gson gson = new Gson();

jsonResponseModel = gson.fromJson(yourStringContent,
                            JsonResponseModel.class);

很容易以这种方式映射。