直接从Java中的模型类创建JSON对象 [英] Creating JSON objects directly from model classes in Java

查看:174
本文介绍了直接从Java中的模型类创建JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to exchange objects of these classes as a JSONObject via Sockets to and from client and server.

有没有我可以直接从模型类的对象创建 JSONObject ,这样对象的字段就成了键,该模型类对象的值成为这个JSONObject的值。

Is there any way I can create JSONObject directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.

示例:

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

我将JSON对象创建为:

And I create JSON Object as:

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

这对我来说是这样的:

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

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

Please note that, in some of my model classes, certain properties are itself an object of other model class. Such as:

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

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

In a case like above, as I'd expect, the yielded JSON object would be:

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

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

I know I could create something like toJSONString() in each model class and have the JSON-friendly string created and manipulate it then, but in my previous experiences of creating RESTful service in Java (which is totally out of context for this question), I could return JSON string from the service method by using @Produces(MediaType.APPLICATION_JSON) and have the method returning object of model class. So it produced JSON string which I could consume at the client end.

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

I was wondering if its possible to get similar behavior in current scenario.

感谢任何帮助或建议。
谢谢。

Any help or suggestion is appreciated. Thanks.

推荐答案

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

Google GSON does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.

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

这篇关于直接从Java中的模型类创建JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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