加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何将Java对象转换为JSONObject?

发布时间:2020-12-14 23:34:51 所属栏目:Java 来源:网络整理
导读:我需要将POJO转换为 JSONObject(org.json.JSONObject) 我知道如何将其转换为文件: ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(new File(file.toString()),registrationData); } catch (JsonGenerationException e) { e.printStack
我需要将POJO转换为 JSONObject(org.json.JSONObject)

我知道如何将其转换为文件:

ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.writeValue(new File(file.toString()),registrationData);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

但这次我不想要一个文件.

解决方法

如果它不是一个太复杂的对象,你可以自己做,没有任何库.以下是一个示例:
public class DemoObject {

    private int mSomeInt;
    private String mSomeString;

    public DemoObject(int i,String s) {

        mSomeInt = i;
        mSomeString = s;
    }

    //... other stuff

    public JSONObject toJSON() {

        JSONObject jo = new JSONObject();
        jo.put("integer",mSomeInt);
        jo.put("string",mSomeString);

        return jo;
    }
}

在代码中:

DemoObject demo = new DemoObject(10,"string");
JSONObject jo = demo.toJSON();

当然,如果你不介意额外的依赖,你也可以使用Google Gson来处理更复杂的东西和不那么繁琐的实现.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读