我的项目中有一些模型类,如Customer
,Product
等,它们有几个字段及其setter-getter方法,我需要将这些类的对象交换为JSONObject via Sockets 与客户端和服务器之间的连接。
有没有办法可以直接从模型类的对象创建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 Object创建为:
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字符串。
我想知道在当前情况下是否有可能获得类似的行为。
感谢任何帮助或建议。 感谢。
答案 0 :(得分:31)
Google GSON这样做;我已经在几个项目中使用它,它很简单,效果很好。它可以在没有干预的情况下对简单对象进行翻译,但也有一种机制可以自定义翻译(在两个方向上)。
Gson g = ...;
String jsonString = g.toJson(new Customer());
答案 1 :(得分:17)
您可以使用 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);
答案 2 :(得分:3)
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();
}
答案 3 :(得分:2)
使用gson来实现这一目标。您可以使用以下代码来获取json
Gson gson = new Gson();
String json = gson.toJson(yourObject);
答案 4 :(得分: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字符串数组。