如何将JSONObject转换为自定义Java类? [英] How can I cast a JSONObject to a custom Java class?

查看:373
本文介绍了如何将JSONObject转换为自定义Java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中(使用json-simple ),我已经成功解析了JSON字符串这是使用JSON.stringify在JavaScript中创建的.看起来像这样:

In Java (using json-simple) I have successfully parsed a JSON string which was created in JavaScript using JSON.stringify. It looks like this:

{"teq":14567,"ver":1,"rev":1234,"cop":15678}

此字符串存储自定义JavaScript对象的状态,我现在希望将其重新构造为纯Java类.它进展不顺利-第一次涉足Java是来自C#背景. :-p

This string is storing the state of a custom JavaScript object which I now wish to re-constitute as a pure Java class. Its not going well - first foray into Java coming from a C# background. :-p

该对象当前采用org.json.simple.JSONObject的形式,因为这是通过JSONParser.parse()操作制成的json-simple.

The object is currently in the form of a org.json.simple.JSONObject since that is what json-simple made from the JSONParser.parse() operation.

如何将这个JSONObject转换为新的Java类?(其定义在下面...)

How can I cast this JSONObject to my new Java class? (the definition of which is below...)

public class MyCustomJSObject {
    public int teq;
    public int ver;
    public int rev;
    public int cop;
}

推荐答案

使用杰克逊库

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper();

    //convert json string to object
    Employee emp = objectMapper.readValue(jsonData, Employee.class); 

这篇关于如何将JSONObject转换为自定义Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆