- 浏览: 1059764 次
- 性别:
- 来自: 南京
文章分类
- 全部博客 (501)
- dwr (6)
- javascript (84)
- oracle (66)
- jsp/servlet (18)
- ant (3)
- 基础知识 (12)
- EXT (10)
- My SQL (10)
- java (71)
- spring (37)
- 学习的对象 (2)
- Linux (24)
- 面试 (1)
- HTML/CSS (11)
- tomcat (11)
- 收藏夹 (2)
- Power Designer (2)
- struts.xml配置文件 (1)
- sturts2 (3)
- myeclipse (8)
- eclipse (7)
- Maven (34)
- SVN (3)
- SAP JCO (2)
- JBOSS (11)
- webservice (8)
- word (1)
- 敏捷开发 (1)
- sybase (4)
- Nexus (3)
- EhCache (3)
- log4j (3)
- Cookie (4)
- Session (4)
- CXF (7)
- AXIS (2)
- SSO (1)
- LDAP (1)
- velocity (2)
- Jquery (5)
- redis (2)
- http (4)
- dojo (1)
- Linux资源监控软件mnon的安装与运用 (1)
- notepad++ (1)
- EA (1)
- UML (1)
- JasperReports (1)
- 权限 (0)
- freemarker (4)
- Spring MVC (1)
- JMS (1)
- activeMQ (1)
- hession (3)
- 安全 (1)
- ibatis (2)
- log (1)
- nginx (1)
最新评论
-
winhbb:
我刚好遇到了一个问题(在可以依赖注入的场合有效):有两个模块A ...
解决Maven项目相互依赖/循环依赖/双向依赖的问题 -
nanjiwubing123:
long3ok 写道你好 XmlOutputFormatter ...
用XStream转换复杂XML -
zhoujianboy:
另外一个方法实现eclipse tomcat 热部署:http ...
eclipse下实现maven项目在tomcat容器热部署方法 -
long3ok:
你好 XmlOutputFormatter 请问这个类是在什么 ...
用XStream转换复杂XML -
ganbo:
总结的好,文章给力。
解决Maven项目相互依赖/循环依赖/双向依赖的问题
因为gson网上的帮助文档打开时比较慢,所以把帮助文档摘录如此,方便查看:
1. 基本类型转化
2.对象转化
Note that you can not serialize objects with circular references since that will result in infinite recursion.
如果要是用json lib的话,上面的代码可以写成如下所示:
Finer Points with Objects
It is perfectly fine (and recommended) to use private fields
There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
This implementation handles nulls correctly
While serialization, a null field is skipped from the output
While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null
If a field is synthetic , it is ignored and not included in JSON serialization or deserialization
Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization
Nested Classes (including Inner Classes)
Gson can serialize static nested classes quite easily.
Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:
NOTE : The above class B can not (by default) be serialized with Gson.
G s o n c a n n o t d e serialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.
The above is possible, but not recommended.
数组例子:
We also support multi-dimensional arrays, with arbitrarily complex element types
综合实例1:
测试:
输出如下:[{"name":"xxlong0","id":"0","age":20,"isOk":false},{"name":"xxlong1","id":"1","age":21,"isOk":false},{"name":"xxlong2","id":"2","age":22,"isOk":false},{"name":"xxlong3","id":"3","age":23,"isOk":false},{"name":"xxlong4","id":"4","age":24,"isOk":false}]
综合实例2:
需求:想将字符串{'tableName' :'ys_index_y','year': '2008','params':'[z_expense,z_expense_profit,z_main_margin]','isOperAll':'false','copyToYear':''}还原成对象OpeerConditions,OpeerConditions对象代码如下所示
因为OperConditions中有属性params,它是一个数组,所以无论是用json lib还是gson都不能直接将上面的字符串还原成OperCondtions对象,可以直接将params分离出来,单独处理,我这里选用此种方法来处理:
json-lib代码如下:
因为JSONArray的toArray()方法返回的是一个Object[]数组,所以先将它转化成list,再转化到String数组。
当然由JSONArray转化成list时也可以使用subList方法,如下所示:
或者可以直接使用JSONArray的iterator() 方法迭代它本身直接得到需要的String数组。
如果使用Gson来完成这一需求,个人感觉更简单,代码如下所示:
Gson可以直接转化成String[]数组,同时转化OperConditions时也比json-lib简单。
还有一点是非常值得注意的,就是你的bean中有boolean属性值时,强烈建议你别像我这个例子中一样命名为以is开头的属性名,这可能给你带来意想不到的错误,关于这一点的详细解说请参看我的文章json lib 学习笔记
【转载地址】
http://ryxxlong.iteye.com/blog/736783
1. 基本类型转化
public static void main(String[] args) { Gson gson = new Gson(); System.out.println(gson.toJson(1)); // ==> prints 1 System.out.println(gson.toJson("abcd"));// ==> prints "abcd" System.out.println(gson.toJson(new Long(10)));// ==> prints 10 int[] values = { 1 }; System.out.println(gson.toJson(values));// ==> prints [1] System.out.println("============"); int one = gson.fromJson("1", int.class); Integer one1 = gson.fromJson("1", Integer.class); Long one2 = gson.fromJson("1", Long.class); String str = gson.fromJson("\"abc\"", String.class); String anotherStr = gson.fromJson("[\"abc\"]", String.class); int[] ints = gson.fromJson("[1,2,3,4,5]", int[].class); Boolean b = gson.fromJson("false", Boolean.class); System.out.println(b == false); //==> prints true }
2.对象转化
public class BagOfPrimitives { private int value1 = 1; private String value2 = "abc"; //是用于声明变量在序列化的时候不被存储 private transient int value3 = 3; BagOfPrimitives() { // no-args constructor } public static void main(String[] args) { BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); System.out.println(json); //==> json is {"value1":1,"value2":"abc"} BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); System.out.println(obj2.value1); System.out.println(obj2.value2); System.out.println(obj2.value3);//==>3 String json1 = "{'value1':1,'value2':'abc','value3':4}"; BagOfPrimitives obj3 = gson.fromJson(json1, BagOfPrimitives.class); System.out.println(obj3.value1); System.out.println(obj3.value2); System.out.println(obj3.value3); //==>3 } }
Note that you can not serialize objects with circular references since that will result in infinite recursion.
如果要是用json lib的话,上面的代码可以写成如下所示:
String json1 = "{'value1':1,'value2':'abc','value3':4}"; JSONObject jsonObj = JSONObject.fromObject( json1 ); BagOfPrimitives obj3 = (BagOfPrimitives) JSONObject.toBean( jsonObj, BagOfPrimitives.class );
Finer Points with Objects
It is perfectly fine (and recommended) to use private fields
There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
This implementation handles nulls correctly
While serialization, a null field is skipped from the output
While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null
If a field is synthetic , it is ignored and not included in JSON serialization or deserialization
Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization
Nested Classes (including Inner Classes)
Gson can serialize static nested classes quite easily.
Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:
public class A { public String a; class B { public String b; public B() { // No args constructor for B } } }
NOTE : The above class B can not (by default) be serialized with Gson.
G s o n c a n n o t d e serialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.
public class InstanceCreatorForB implements InstanceCreator<A.B> { private final A a; public InstanceCreatorForB(A a) { this.a = a; } public A.B createInstance(Type type) { return a.new B(); } }
The above is possible, but not recommended.
数组例子:
Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; (Serialization) gson.toJson(ints); ==> prints [1,2,3,4,5] gson.toJson(strings); ==> prints ["abc", "def", "ghi"] (Deserialization) int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); ==> ints2 will be same as ints
We also support multi-dimensional arrays, with arbitrarily complex element types
综合实例1:
public class ExampleBean { private String name; private String id; private int age; private boolean isOk; public ExampleBean(String name, String id, int age, boolean isOk) { super(); this.name = name; this.id = id; this.age = age; this.isOk = isOk; } public ExampleBean() { } //setter和getter方法 }
测试:
public static void main(String[] args) { Gson gson = new Gson(); List<ExampleBean> list = new ArrayList<ExampleBean>(); for (int i = 0; i < 5; i++) { String name = "xxlong" + i; int age = 20 + i; ExampleBean bean = new ExampleBean(name, i + "", age); list.add(bean); } Type listType = new TypeToken<List<ExampleBean>>() { }.getType(); //将list转化成json字符串 String json = gson.toJson(list); System.out.println(json); //将json字符串还原成list List<ExampleBean> list2 = gson.fromJson(json, listType); }
输出如下:[{"name":"xxlong0","id":"0","age":20,"isOk":false},{"name":"xxlong1","id":"1","age":21,"isOk":false},{"name":"xxlong2","id":"2","age":22,"isOk":false},{"name":"xxlong3","id":"3","age":23,"isOk":false},{"name":"xxlong4","id":"4","age":24,"isOk":false}]
综合实例2:
需求:想将字符串{'tableName' :'ys_index_y','year': '2008','params':'[z_expense,z_expense_profit,z_main_margin]','isOperAll':'false','copyToYear':''}还原成对象OpeerConditions,OpeerConditions对象代码如下所示
public class OperConditions { private String tableName; private String year; private String[] params; private boolean isOperALl; private String copyToYear; public OperConditions() { } public OperConditions(String tableName, String year, String[] params, boolean isOperALl, String copyToYear) { super(); this.tableName = tableName; this.year = year; this.params = params; this.setOperALl(isOperALl); this.copyToYear = copyToYear; } //getter和setter方法 }
因为OperConditions中有属性params,它是一个数组,所以无论是用json lib还是gson都不能直接将上面的字符串还原成OperCondtions对象,可以直接将params分离出来,单独处理,我这里选用此种方法来处理:
json-lib代码如下:
public static void main(String[] args) { String json = "{'tableName' :'ys_index_y','year': '2008','isOperAll':'false','copyToYear':''}"; JSONObject jsonObj = JSONObject.fromObject( json ); OperConditions conditions = (OperConditions) JSONObject.toBean( jsonObj, OperConditions.class ); System.out.println(conditions.isOperALl() == false); //==>输出为true String json1 = "['z_expense','z_expense_profit','z_main_margin']"; JSONArray jsonArray = JSONArray.fromObject(json1); //List<String> list = jsonArray.toList(jsonArray); //这个方法也可以 List<String> list = jsonArray.toList(jsonArray,String.class); conditions.setParams(list.toArray(new String[0])); System.out.println(conditions.getParams()[0]); //==>输出为z_expense }
因为JSONArray的toArray()方法返回的是一个Object[]数组,所以先将它转化成list,再转化到String数组。
当然由JSONArray转化成list时也可以使用subList方法,如下所示:
List<String> list = jsonArray.subList(0, jsonArray.size());
或者可以直接使用JSONArray的iterator() 方法迭代它本身直接得到需要的String数组。
如果使用Gson来完成这一需求,个人感觉更简单,代码如下所示:
public static void main(String[] args) { String json = "{'tableName' :'ys_index_y','year': '2008','isOperAll':'false','copyToYear':''}"; Gson gson = new Gson(); OperConditions conditions = gson.fromJson(json, OperConditions.class); System.out.println(conditions.isOperALl() == false); // ==>输出为true String json1 = "['z_expense','z_expense_profit','z_main_margin']"; String[] params = gson.fromJson(json1,String[].class); conditions.setParams(params); System.out.println(conditions.getParams()[0]); // ==>输出为z_expense }
Gson可以直接转化成String[]数组,同时转化OperConditions时也比json-lib简单。
还有一点是非常值得注意的,就是你的bean中有boolean属性值时,强烈建议你别像我这个例子中一样命名为以is开头的属性名,这可能给你带来意想不到的错误,关于这一点的详细解说请参看我的文章json lib 学习笔记
【转载地址】
http://ryxxlong.iteye.com/blog/736783
发表评论
-
个人草稿使用
2017-08-19 09:02 0深入理解JVM: http://www.cnblogs.co ... -
Thread.setDaemon详解
2015-04-24 21:31 894java中线程分为两种类型:用户线程和守护线程。通过Threa ... -
怎么使用 ConcurrentHashMap 才能是线程安全的?
2015-04-13 11:54 1498public class test { public ... -
21,tomcat关闭钩子
2014-12-31 10:36 722在很多环境下,在关闭应用程序的时候需要做一些清理工作。问题在于 ... -
Java NIO使用及原理分析 (一) 【转载】
2014-10-24 00:04 482【转载】: http://blog.csdn.net/wuxi ... -
Java 两个集合取交集
2014-10-14 21:16 3113public static Set intersectionS ... -
Calendar类roll和add的区别
2014-10-10 22:28 487import java.text.SimpleDateForm ... -
Gson通过借助TypeToken获取泛型参数的类型的方法
2014-09-30 00:26 625[size=medium]最近在使用Goo ... -
HashMap的遍历效率讨论
2014-09-27 20:41 824经常遇到对HashMap中的key和value值对的遍历操作, ... -
Java 泛型
2014-06-26 12:44 851关键字说明 ? 通配符类型 <? extends T&g ... -
Java泛型集合的理解
2014-06-26 00:05 501[size=medium]什么是泛型? 泛型(Generic ... -
关于java字节码框架ASM的学习
2014-06-19 19:22 881一、什么是ASM ASM是一个java字节码操纵框架, ... -
Java动态代理详解
2014-06-19 17:41 853Java动态代理详解: http: ... -
Java内存,字符串文章收集
2014-06-18 16:24 705java--String常量池问题的几个例子 . http:/ ... -
Java内存解析
2014-06-18 11:48 767栈、堆、常量池等虽同 ... -
Java的堆与非堆内存
2014-01-07 10:59 711堆(Heap)和非堆(Non-heap)内存 按照官方的说法: ... -
JMX 资料收集
2014-01-07 10:53 442JavaSky的专栏 http://blog.csdn.net ... -
JAVA 注解示例 详解
2013-11-12 09:36 820注解(Annotation) 为我们在代码中天界信息提供了 ... -
Java 泛型详解
2013-11-11 22:35 795http://www.360doc.com/content/1 ... -
Java中的Enum的使用与分析
2013-11-09 12:49 813enum枚举类型:在实际问 ...
相关推荐
然而,随着技术的发展,虽然json-lib在当时是一个流行的JSON处理库,但现在已有其他更先进的替代品,如Gson、Jackson和Fastjson等,它们在性能、易用性和功能上都有所提升。因此,对于新项目来说,选择这些更新的库...
为了方便地处理JSON数据,Java社区提供了多个优秀的JSON库,包括Gson、Fastjson、Jackson和json-lib。这四大JSON库各有特点,适应不同的使用场景。 1. Gson: Gson是Google提供的一个开源库,它能够将Java对象转换...
在文件列表中的"jsonlib需要jar包",这可能是指包含了`json-lib`库及其所有依赖的JAR文件。在实际项目中,将这些JAR文件添加到项目的类路径(classpath)中,就可以使用`json-lib`提供的功能,而无需通过Maven或其他...
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,被广泛用于Web应用...尽管现在有更现代的替代品如Gson、Jackson等,但在某些场景下,JSON-lib仍然是一个可靠的选择,特别是对于需要向后兼容的老项目。
4. **性能优化**:虽然json-lib是一个强大的库,但在处理大量数据时,其性能可能不如其他更现代的库如Jackson或Gson。然而,对于小型项目或对性能要求不高的场景,json-lib仍是一个可行的选择。 在Android开发中,...
JSON库如json-lib-2.4是Java开发者在处理JSON数据时的重要工具,它提供了一系列API,使得JSON与Java对象之间的转换变得更加简单。本文将深入探讨json-lib-2.4及其在Java开发中的应用。 首先,json-lib-2.4是一个...
4. **XML与JSON互转**:除了基本的JSON操作,`json-lib`还提供了XML与JSON之间的转换功能,这对于需要在XML和JSON之间进行数据交换的应用非常有用。 5. **依赖包的集成**:`json-lib-2.3-jdk15`开发包包含了所有...
`json-lib`库的使用使得Java开发者在处理JSON数据时更加便捷,但需要注意的是,随着Java生态的发展,现在更流行的是使用Jackson、Gson或Google的AutoValue库来处理JSON,它们提供了更多特性和更好的性能。...
在处理复杂的Java对象和大量的数据时,`json-lib`提供了一套完整的解决方案,但随着技术的发展,还有其他更现代的JSON库如Gson、Jackson和Fastjson等,它们在性能和易用性上可能更有优势。因此,在选择JSON库时,应...
在Java中,JSON库如json-lib 2.4可以帮助开发者有效地处理JSON数据,进行数据的序列化与反序列化操作。本文将深入探讨json-lib 2.4这个jar包在Java开发中的应用。 json-lib是一个Java库,它提供了多种Java集合(如...
7. **性能优化**:虽然JSON-Lib功能强大,但相比其他更现代的JSON库(如Jackson或Gson),其性能可能略低。因此,在性能敏感的应用中,可能需要权衡其便利性和效率。 总之,`json-lib-2.4 jar`为Java开发者提供了一...
Gson是Google提供的一个开源库,它可以直接将Java对象转换成JSON字符串,也可以将JSON字符串反序列化为Java对象。Gson的强大之处在于其灵活性和丰富的功能,例如支持自定义类型适配器、处理日期时间、以及支持泛型...
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,被广泛用于Web服务和服务器端...在现代的Java开发中,虽然有其他更现代的JSON库如Gson和Jackson,但`json-lib`仍然在一些遗留系统或特定场景下被使用。
1. **Jackson或Gson库**:这两个是其他流行的JSON库,可能会被`json-lib`用作底层实现的一部分,提供JSON序列化和反序列化的功能。 2. **Eclipse Collections**:可能用于提供高效的数据结构,如集合和映射,用于...
这个学习笔记主要围绕`json-lib`的使用方法和关键特性进行阐述。 首先,`json-lib`支持多种Java对象到JSON的转换,包括基本类型、数组、集合、Map以及自定义的Java类。例如,你可以通过以下方式将一个HashMap转换为...
通常,这样的集合可能包括json-lib自身的jar,以及它依赖的其他库,如Jackson、Gson、org.json等,因为Json-lib可能利用了这些库的功能来实现其功能。 具体到这个压缩包,文件名为“json.jar”,这很可能是json-lib...
需要注意的是,虽然`json-lib`在过去被广泛应用,但随着技术的发展,现在更推荐使用如Gson、Jackson或Fastjson这样的现代JSON库,它们通常具有更好的性能和更丰富的功能。然而,对于一些老旧的项目或者需要与旧系统...
然而,随着时间的发展,json-lib的更新相对较慢,社区支持可能不如其他更现代的JSON库如Gson或Jackson活跃。这些新库提供了更多特性,比如类型安全的转换、注解支持以及更高效的性能。 总的来说,"json-lib-2.1-jdk...
JSON(JavaScript ...然而,随着技术的发展,现在有许多其他流行的JSON库,如Gson、Jackson和Fastjson,它们在性能和易用性方面可能更具优势。在选择JSON库时,开发者应根据项目需求、性能要求和团队熟悉度来决定。
- **JSON与XML的互转**:`json-lib`还支持JSON和XML之间的转换,这对于那些需要在两种格式间切换的应用场景非常实用。 - **类型适配器**:库提供了一种机制,允许自定义特定类型(如自定义类)到JSON的转换,通过...