Java 将类转换为 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24330718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:36:02  来源:igfitidea点击:

Convert class into a JSONObject

javajsongsonjsonobject

提问by TTransmit

I have several classes like this. I want to convert the classes into JSONObject format.

我有好几个这样的课。我想将类转换为 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;
    }
}

I know that I can convert these classes to JSONObject format as follows:

我知道我可以将这些类转换为 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();
    }

The problem is that I need to do this for a lot of different classes that are much longer than this across a lot of files. Can I use GSON to fill the JSONObject from myClass so that I don't need to edit every time the class structure changes?

问题是我需要为许多不同的类执行此操作,这些类在很多文件中都比这长得多。我可以使用 GSON 来填充 myClass 中的 JSONObject 以便每次类结构更改时都不需要进行编辑吗?

The following returns a JSON string but I need it as an Object as when I send it to the system that sends the requests via a REST API it sends with unwanted quotation marks.

以下返回一个 JSON 字符串,但我需要它作为一个对象,因为当我将它发送到通过 REST API 发送请求的系统时,它使用不需要的引号发送。

User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);

When I use this in another JSON builder that asks for an Object I get

当我在另一个请求对象的 JSON 构建器中使用它时,我得到

{"request":"{"id":"100","name":"Test Name","email":"[email protected]"}"}

When I want

当我想要

{"request":{"id":"100","name":"Test Name","email":"[email protected]"}}

回答by Patrick M

Here is a crude example you can use to use Reflection to build the JSONObject..

这是一个粗略的示例,您可以使用反射来构建 JSONObject..

Warning it's not pretty and does not contain really type-safety.

警告它不漂亮并且不包含真正的类型安全。

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;
}

Here is an example usage:

这是一个示例用法:

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

Output

输出

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

回答by TTransmit

I found that the following works with GSON:

我发现以下适用于 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();
    }

This is not type safe, however.

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