Android with Volley, Gson : 如何定义 class 以跟随 json 响应
Android with Volley, Gson : how to define class for following json response
我的预期 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));
}
}
}
我的问题是如何写 class 我可以传递 GsonRequest class 并得到响应
我尝试 http://www.jsonschema2pojo.org/ 为我的 json 响应生成 class
现在我提出如下要求
GsonRequest<MyClass> gsonRequest = new GsonRequest<MyClass>(url,MyClass.class, null,createMyReqSuccessListener(), createMyReqErrorListener());
我的 Response Listener 函数
private Response.Listener<MyClass> createMyReqSuccessListener() {
return new Response.Listener<MyClass>()
{
@Override
public void onResponse(MyClass response) {
txtView.setText("success" + response.first_name);
}
};
}
Class 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;
}
}
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;
}
}
像这样
有有用的 Web 服务可以生成 类 http://www.jsonschema2pojo.org/
只是 select 源类型:JSON 和注释样式:GSON
这是为您的示例所做的:
-----------------------------------com.example.Contact.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Contact {
@Expose
private String id;
@Expose
private String name;
@Expose
private String email;
@Expose
private String address;
@Expose
private String gender;
@Expose
private Phone phone;
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* @param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @return
* The address
*/
public String getAddress() {
return address;
}
/**
*
* @param address
* The address
*/
public void setAddress(String address) {
this.address = address;
}
/**
*
* @return
* The gender
*/
public String getGender() {
return gender;
}
/**
*
* @param gender
* The gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
*
* @return
* The phone
*/
public Phone getPhone() {
return phone;
}
/**
*
* @param phone
* The phone
*/
public void setPhone(Phone phone) {
this.phone = phone;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class Example {
@SerializedName("first_name")
@Expose
private String firstName;
@Expose
private List<Contact> contacts = new ArrayList<Contact>();
/**
*
* @return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The first_name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return
* The contacts
*/
public List<Contact> getContacts() {
return contacts;
}
/**
*
* @param contacts
* The contacts
*/
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
-----------------------------------com.example.Phone.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Phone {
@Expose
private String mobile;
@Expose
private String home;
@Expose
private String office;
/**
*
* @return
* The mobile
*/
public String getMobile() {
return mobile;
}
/**
*
* @param mobile
* The mobile
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
*
* @return
* The home
*/
public String getHome() {
return home;
}
/**
*
* @param home
* The home
*/
public void setHome(String home) {
this.home = home;
}
/**
*
* @return
* The office
*/
public String getOffice() {
return office;
}
/**
*
* @param office
* The office
*/
public void setOffice(String office) {
this.office = office;
}
}
对于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 article and this code。
我的预期 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));
}
}
}
我的问题是如何写 class 我可以传递 GsonRequest class 并得到响应 我尝试 http://www.jsonschema2pojo.org/ 为我的 json 响应生成 class
现在我提出如下要求
GsonRequest<MyClass> gsonRequest = new GsonRequest<MyClass>(url,MyClass.class, null,createMyReqSuccessListener(), createMyReqErrorListener());
我的 Response Listener 函数
private Response.Listener<MyClass> createMyReqSuccessListener() {
return new Response.Listener<MyClass>()
{
@Override
public void onResponse(MyClass response) {
txtView.setText("success" + response.first_name);
}
};
}
Class 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;
}
}
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;
}
}
像这样
有有用的 Web 服务可以生成 类 http://www.jsonschema2pojo.org/ 只是 select 源类型:JSON 和注释样式:GSON
这是为您的示例所做的:
-----------------------------------com.example.Contact.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Contact {
@Expose
private String id;
@Expose
private String name;
@Expose
private String email;
@Expose
private String address;
@Expose
private String gender;
@Expose
private Phone phone;
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* @param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @return
* The address
*/
public String getAddress() {
return address;
}
/**
*
* @param address
* The address
*/
public void setAddress(String address) {
this.address = address;
}
/**
*
* @return
* The gender
*/
public String getGender() {
return gender;
}
/**
*
* @param gender
* The gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
*
* @return
* The phone
*/
public Phone getPhone() {
return phone;
}
/**
*
* @param phone
* The phone
*/
public void setPhone(Phone phone) {
this.phone = phone;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class Example {
@SerializedName("first_name")
@Expose
private String firstName;
@Expose
private List<Contact> contacts = new ArrayList<Contact>();
/**
*
* @return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The first_name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return
* The contacts
*/
public List<Contact> getContacts() {
return contacts;
}
/**
*
* @param contacts
* The contacts
*/
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
-----------------------------------com.example.Phone.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
@Generated("org.jsonschema2pojo")
public class Phone {
@Expose
private String mobile;
@Expose
private String home;
@Expose
private String office;
/**
*
* @return
* The mobile
*/
public String getMobile() {
return mobile;
}
/**
*
* @param mobile
* The mobile
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
*
* @return
* The home
*/
public String getHome() {
return home;
}
/**
*
* @param home
* The home
*/
public void setHome(String home) {
this.home = home;
}
/**
*
* @return
* The office
*/
public String getOffice() {
return office;
}
/**
*
* @param office
* The office
*/
public void setOffice(String office) {
this.office = office;
}
}
对于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 article and this code。