32

我的项目中有一些模型类,如Customer,Product等,它们有几个字段及其 setter-getter 方法,我需要通过套接字将这些类的对象作为 JSONObject 交换到客户端和服务器。

有什么方法可以JSONObject直接从模型类的对象创建,使得对象的字段成为键,该模型类对象的值成为这个 JSONObject 的值。

例子:

Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....

我将 JSON 对象创建为:

JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.

这让我得到了类似的东西:

{"name":"Foo Bar","city":"Atlantis"...}

请注意,在我的一些模型类中,某些属性本身就是其他模型类的对象。如:

Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);

在上述情况下,正如我所料,生成的 JSON 对象将是:

{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}

我知道我可以toJSONString()在每个模型类中创建类似的东西,然后创建对 JSON 友好的字符串并对其进行操作,但是在我之前在 Java 中创建 RESTful 服务的经验中(这完全脱离了这个问题的上下文),我可以返回使用来自服务方法的 JSON 字符串,@Produces(MediaType.APPLICATION_JSON)并具有模型类的方法返回对象。所以它生成了 JSON 字符串,我可以在客户端使用它。

我想知道在当前情况下是否有可能获得类似的行为。

4

5 回答 5

39

谷歌 GSON这样做;我已经在几个项目中使用过它,它很简单而且效果很好。它可以在没有干预的情况下对简单对象进行翻译,但也有一种自定义翻译的机制(双向)。

Gson g = ...;
String jsonString = g.toJson(new Customer());
于 2012-06-07T11:20:45.947 回答
21

您可以为此使用Gson

Maven依赖:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>

Java代码:

Customer customer = new Customer();
Product product = new Product();

// Set your values ...

Gson gson = new Gson();
String json = gson.toJson(customer);

Customer deserialized = gson.fromJson(json, Customer.class);
于 2012-06-07T11:20:35.703 回答
4
    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();
    }
于 2016-03-09T08:12:26.240 回答
2

使用gson来实现这一点。您可以使用以下代码获取json然后

Gson gson = new Gson();
String json = gson.toJson(yourObject);
于 2012-06-07T11:22:08.560 回答
0

我使用XStream Parser 来

    Product p = new Product();
    p.setName("FooBar Cookies");
    p.setProductType("Food");
    c.setBoughtProduct(p);

    XStream xstream = new XStream(new JettisonMappedXmlDriver());
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("p", Product.class);
    String jSONMsg=xstream.toXML(product);
    System.out.println(xstream.toXML(product));

这将为您提供 JSON 字符串数组。

于 2012-06-07T11:50:42.220 回答