直接从Java中的模型类创建JSON对象

我的项目中有一些模型类,如CustomerProduct等,它有几个字段及其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服务的经验中(这完全脱离了这个问题的上下文),我可以使用@Produces(MediaType.APPLICATION_JSON)从服务方法返回JSON字符串,并让方法返回模型类的对象。 所以它产生了我可以在客户端使用的JSON字符串。

我想知道它是否有可能在当前场景中获得类似的行为。

任何帮助或建议表示赞赏。 谢谢。

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

 Gson g = ...; String jsonString = g.toJson(new Customer()); 

您可以使用Gson

Maven依赖:

  com.google.code.gson gson 2.8.0  

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

使用gson实现这一目标。 您可以使用以下代码来获取json

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

我使用过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字符串数组。