将类转换为JSONObject

时间:2014-06-20 15:26:10

标签: 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;
    }
}

我知道我可以将这些类转换为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字符串但我需要它作为一个Object,就像我将它发送到通过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"}}

3 个答案:

答案 0 :(得分: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();
    }

然而,这不是类型安全的。

答案 1 :(得分:2)

这是一个粗略的例子,您可以使用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;
}

以下是一个示例用法:

User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));

输出

{
   "id": "",
   "name": "",
   "email": ""
}

答案 2 :(得分:0)

尝试使用此代码:

// 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());