[英]Convert class into a JSONObject
我有好幾個這樣的課。 我想將類轉換為 JSONObject 格式。
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("id")
private Integer mId;
@SerializedName("name")
private String mName = "";
@SerializedName("email")
private String mEmail;
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
}
我知道我可以將這些類轉換為 JSONObject 格式,如下所示:
User user = new User();
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", user.getId());
jsonObj.put("name", user.getName());
jsonObj.put("email", user.getEmail());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
問題是我需要為許多不同的類執行此操作,這些類在很多文件中都比這長得多。 我可以使用 GSON 來填充 myClass 中的 JSONObject 以便每次類結構更改時都不需要進行編輯嗎?
下面返回一個 JSON 字符串,但我需要它作為一個對象,因為當我將它發送到通過 REST API 發送請求的系統時,它使用不需要的引號發送。
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
當我在另一個請求對象的 JSON 構建器中使用它時,我得到
{"request":"{"id":"100","name":"Test Name","email":"test@example.com"}"}
當我想要
{"request":{"id":"100","name":"Test Name","email":"test@example.com"}}
我發現以下適用於 GSON:
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
然而,這不是類型安全的。
這是一個粗略的示例,您可以使用反射來構建 JSONObject..
警告它不漂亮並且不包含真正的類型安全。
public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
JSONObject object = new JSONObject();
Class<?> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof SerializedName){
SerializedName myAnnotation = (SerializedName) annotation;
String name = myAnnotation.value();
Object value = field.get(obj);
if(value == null)
value = new String("");
object.put(name, value);
}
}
}
return object;
}
這是一個示例用法:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
輸出
{
"id": "",
"name": "",
"email": ""
}
嘗試使用此代碼:
// Returns the JSON in a String
public String getJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
// Builds the Model Object from the JSON String
MyModel model =new MyModel();
JSONObject j = new JSONObject(model.getJSON());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.