TTr*_*mit 5 java json gson 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以将这些类转换为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();
}
Run Code Online (Sandbox Code Playgroud)
问题是我需要在许多不同的类中执行此操作,这些类在很多文件中都比这长得多.我可以使用GSON从myClass填充JSONObject,这样每次类结构更改时我都不需要编辑吗?
以下命令返回一个JSON字符串,但我需要它作为一个Object,就像我将它发送到通过REST API发送请求的系统一样,它发送带有不需要的引号.
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
Run Code Online (Sandbox Code Playgroud)
当我在另一个请求我得到的对象的JSON构建器中使用它时
{"request":"{"id":"100","name":"Test Name","email":"test@example.com"}"}
Run Code Online (Sandbox Code Playgroud)
当我想要的时候
{"request":{"id":"100","name":"Test Name","email":"test@example.com"}}
Run Code Online (Sandbox Code Playgroud)
TTr*_*mit 17
我发现以下适用于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();
}
Run Code Online (Sandbox Code Playgroud)
但是,这不是类型安全的.
这是一个粗略的示例,您可以使用 Reflection 来构建 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;
}
Run Code Online (Sandbox Code Playgroud)
这是一个用法示例:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
Run Code Online (Sandbox Code Playgroud)
输出
{
"id": "",
"name": "",
"email": ""
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36014 次 |
| 最近记录: |