Android与Volley,Gson:如何定义类以跟随json响应

时间:2015-09-07 09:00:36

标签: android json gson android-volley

我期待的Json回应

{
  "first_name": "Rajesh",
  "contacts": [
    {
      "id": "c200",
      "name": "rajesh",
      "email": "ravi@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender": "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    },
    {
      "id": "c201",
      "name": "ravi",
      "email": "ravi_depp@gmail.com",
      "address": "xx-xx-xxxx,x - street, x - country",
      "gender": "male",
      "phone": {
        "mobile": "+91 0000000000",
        "home": "00 000000",
        "office": "00 000000"
      }
    }
  ]
}

GsonRequest Class发出请求并获得响应

public class GsonRequest<T> extends Request<T> {

    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;


    public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
        Listener<T> listener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);

        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(gson.fromJson(json, clazz),
                HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

我的问题是如何编写可以传递GsonRequest类并获得响应的类 我尝试http://www.jsonschema2pojo.org/为我的json响应生成类

目前我正在提出以下要求

  GsonRequest<MyClass> gsonRequest = new GsonRequest<MyClass>(url,MyClass.class, null,createMyReqSuccessListener(), createMyReqErrorListener());

我的响应侦听器功能

private Response.Listener<MyClass> createMyReqSuccessListener() {
        return new Response.Listener<MyClass>()
        {
            @Override
            public void onResponse(MyClass response) {

                txtView.setText("success" + response.first_name);
            }
        };
    }       

json响应的类

public class MyClass {
    public String first_name;
    public List<Contact> contacts;

    public class Contact {
        public String id;
        public String name;
        public String email;
        public String address;
        public String gender;
        public Phone phone;
    }

    public class Phone {
        public String mobile;
        public String home;
        public String office;
    }
}

3 个答案:

答案 0 :(得分:0)

public class Response {
    public String first_name;
    public List<Contact> contacts;

    public class Contact {
        public String id;
        public String name;
        public String email;
        public String address;
        public String gender;
        public Phone phone;
    }

    public class Phone {
        public String mobile;
        public String home;
        public String office;
    }
}
像这样

答案 1 :(得分:0)

有用于生成类http://www.jsonschema2pojo.org/的有用Web服务 只需选择源类型:JSON和注释样式:GSON

以下是您的示例:

/src

答案 2 :(得分:0)

对于Json对象:

public static GsonRequest<DummyObject> getDummyObject
(
        Response.Listener<DummyObject> listener,
        Response.ErrorListener errorListener
)
{
    final String url = "http://www.mocky.io/v2/55973508b0e9e4a71a02f05f";

    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
            .create();

    return new GsonRequest<>
            (
                    url,
                    new TypeToken<DummyObject>() {}.getType(),
                    gson,
                    listener,
                    errorListener
            );
}

对于JSON数组:

public static GsonRequest<ArrayList<DummyObject>> getDummyObjectArray
(
        Response.Listener<ArrayList<DummyObject>> listener,
        Response.ErrorListener errorListener
)
{
    final String url = "http://www.mocky.io/v2/5597d86a6344715505576725";

    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
            .create();

    return new GsonRequest<>
            (
                    url,
                    new TypeToken<ArrayList<DummyObject>>() {}.getType(),
                    gson,
                    listener,
                    errorListener
            );
}

Java对象:

public class DummyObject
{
    private String mTitle;
    private String mBody;

    public String getTitle()
    {
        return mTitle;
    }

    public void setTitle(String title)
    {
        mTitle = title;
    }

    public String getBody()
    {
        return mBody;
    }

    public void setBody(String body)
    {
        mBody = body;
    }
}

解串器(并非总是必要):

public class DummyObjectDeserializer implements JsonDeserializer<DummyObject>
{
    @Override
    public DummyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException
    {
        final DummyObject dummyObject = new DummyObject();
        final JsonObject jsonObject = json.getAsJsonObject();

        dummyObject.setTitle(jsonObject.get("title").getAsString());
        dummyObject.setBody(jsonObject.get("body").getAsString());

        return dummyObject;
    }
}

如果您有任何问题,请查看this articlethis code