`
envy2002
  • 浏览: 151673 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

jsonlib json-->object,忽略object中没有的属性

 
阅读更多

Friday, May 27, 2011

Ignore missing properties with Json-Lib

Introduction

When you're writing your own client and server protocol, you have to exchange data between them. There are many formats available (csv, xml, serialized objects...) and you can always define your own protocol.
One format that has been getting more popular recently is JSON (JavaScript Object Notation, see http://en.wikipedia.org/wiki/JSON). It's a text format that allows objects to be serialized in a human-readable form. There's a library for Java called Json-lib (http://json-lib.sourceforge.net/) that performs this serialization for you. This allows you to exchange JSON between your server and client without having to write any JSON code.

The Json-lib library

You can find some examples on how to use Json-lib here: http://json-lib.sourceforge.net/snippets.html. I use it like this:
On the server (serialize to JSON):
1
2
3
User user = ...; //get the user from database
String json = JSONObject.fromObject(user).toString();
//Send the json to the client
Then on the client:
1
2
JSONObject jo = JSONObject.fromObject(response);
User user = (User) JSONObject.toBean(jo, User.class);
As you can see it's pretty straight-forward and it works well, as long as the class definitions (in this case: the User class) are the same on the server and the client. As you can imagine this is not always the case: you will sometimes add new properties to the class while users are still using the old definition of your class on their client. If this is the case (you are sending properties from the server that don't exist on the client class), you get slapped with this exception:
1
net.sf.json.JSONException: java.lang.NoSuchMethodException: Unknown property on class
You can fix this exception by adding an exclude filter on the server that doesn't send certain properties (see http://json-lib.sourceforge.net/snippets.html for how to do this), but this isn't a solution in our case: we want to send the properties so people who have the newer version of the client can use them.

The solution

After searching for a way of telling Json-lib to ignore missing properties and not finding it, I decided the best approach would be to create my own PropertySetStrategy. A PropertySetStrategy defines how Json-lib sets the properties on your objects. The default strategy works pretty well, except that it throws an exception when a property is not found. So I decided to create a wrapper around this default PropertySetStrategy that ignores any exceptions happening when setting a property.
This is my PropertySetStrategyWrapper:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import net.sf.json.JSONException;
import net.sf.json.util.PropertySetStrategy;
 
public class PropertyStrategyWrapper extends PropertySetStrategy {
 
    private PropertySetStrategy original;
 
    public PropertyStrategyWrapper(PropertySetStrategy original) {
        this.original = original;
    }
 
    @Override
    public void setProperty(Object o, String string, Object o1) throws JSONException {
        try {
            original.setProperty(o, string, o1);
        } catch (Exception ex) {
            //ignore
        }
    }
}
As you can see I ignore any exceptions that happen on a set. You can always log the exceptions if you prefer.
Now all we need to do is tell Json-lib to use our wrapper. Our client code now looks like this:
1
2
3
4
5
JSONObject jo = JSONObject.fromObject(response);
JsonConfig cfg = new JsonConfig();
cfg.setPropertySetStrategy(new PropertyStrategyWrapper(PropertySetStrategy.DEFAULT));
cfg.setRootClass(User.class);
User user = (User) JSONObject.toBean(jo, cfg);
分享到:
评论
1 楼 lp385267935 2013-04-10  
不错  很好用~3Q

相关推荐

    json-lib-2.4-jdk15.jar

    5. **自定义转换规则**:用户可以通过实现`JsonConfig`类中的方法,自定义Java对象到JSON的转换规则,如忽略某些字段或者自定义转换策略。 6. **性能优化**:json-lib针对不同的JDK版本提供了优化,比如这个2.4-jdk...

    json-lib-2.2.2-jdk15.jar

    3. **自定义序列化**:通过实现JSONAware接口或使用JSONSerializer的transform方法,开发者可以定制JSON序列化过程,比如忽略某些属性或者自定义特定字段的格式。 4. **性能优化**:虽然json-lib是一个强大的库,但...

    json-lib-2.4-jdk15及其依赖jar包

    在这个压缩包"json-lib-2.4-jdk15及其依赖jar包.rar"中,你将找到json-lib的2.4版本,这是一个针对JDK 1.5的优化版本,确保在较旧的Java环境中也能正常工作。除此之外,这个压缩包还可能包含其运行所需的依赖库,...

    json-lib-2.2.3帮助api

    通过阅读`json-lib-2.2.3-jdk15-javadoc`中的文档,你可以深入理解每个类和方法的具体用法,包括参数、返回值、示例代码等,从而更好地在实际项目中运用json-lib处理JSON数据。此外,文档通常还包括常见问题解答和...

    json-lib相关所有包

    本文将深入探讨json-lib库及其在Java开发中的应用。 json-lib是一个开源的Java库,它允许Java程序员将Java对象转换为JSON格式,反之亦然。这个库特别适用于那些需要在服务器端和客户端之间传递数据的Web应用程序。...

    struts2 相关jar包 包含json-lib-2.1.jar+struts2-json-plugin-2.1.8.1.jar

    这个压缩包包含了两个关键的组件:json-lib-2.1.jar和struts2-json-plugin-2.1.8.1.jar,它们是Struts2支持JSON(JavaScript Object Notation)序列化和反序列化的关键。 1. **json-lib-2.1.jar**: JSON是一种轻...

    json lib 开发包

    4. **自定义序列化和反序列化**:开发者可以根据需求定制JSON序列化和反序列化的过程,比如忽略某些属性,或者自定义转换规则。 5. **性能优化**:虽然json-lib在处理大量数据时可能不如一些现代的JSON库(如...

    JS和JAVA使用JSON方法解析汇报.docx

    - Java Bean -> JSON Object - Java Collection/Array -> JSON Array - Java Map -> JSON Object - Java String -> JSON String - Java Number -> JSON Number - Java Boolean -> JSON Boolean - Java null -...

    java json-lib解决无循环的探索例子

    Java中的json-lib库是处理JSON数据的一个常用工具,它提供了将Java对象转换为JSON字符串以及从JSON字符串反序列化回Java对象的功能。然而,在处理复杂的嵌套数据结构时,如果不小心可能会导致无限循环的问题。 在...

    jsonLib支持库

    在Java开发中,jsonLib是一个广泛使用的JSON处理库,它提供了丰富的API来帮助开发者进行JSON的序列化和反序列化操作。这篇博文主要探讨jsonLib支持库在Java开发中的应用和关键功能。 首先,jsonLib作为一个开源工具...

    jsonlib需要jar包.zip

    `jsonlib需要jar包.zip`是一个包含jsonlib库的压缩文件,它提供了Java开发人员所需的依赖,以便在项目中使用JSONLib。在Java应用中,我们通常需要将.jar文件添加到项目的类路径(Classpath)中,以便能够调用库中的...

    json插件与配置文件

    JSON库如jsonlib在Java开发中扮演着重要角色,它允许开发者方便地解析、生成JSON格式的数据。本文将深入探讨jsonlib这个特定的JSON处理库,并介绍如何配置和使用它。 **jsonlib简介** jsonlib是一个Java库,专门...

    JSON-LIB快速入门(转)

    在实际使用中,注意JSON-LIB对null值的处理,有些版本默认会忽略null值。如果需要包含null,可能需要配置转换器或使用特定方法。 总之,JSON-LIB是一个强大的Java库,为处理JSON数据提供了便利。通过了解其基本...

    使用json-lib进行Java和JSON之间的转换

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于Web应用程序中,因为它易于人阅读和编写,同时也易于机器解析和生成。在Java中,处理JSON数据时,我们通常会使用各种库,比如json-lib。这...

    JSON-LIB快速入门

    在JSON-LIB的快速入门中,我们首先需要了解JSON的基本结构。JSON主要由两种基本类型构成:对象和数组。对象是以花括号{}包围的键值对集合,键是字符串,值可以是各种JSON数据类型,如字符串、数字、布尔值、null、...

    json-lib之jar包,源代码及API文档

    JSON(JavaScript Object Notation)是一种轻量级的...有了`json-lib.jar`和详细的API文档,开发者可以更高效地集成JSON功能到他们的项目中,无论是简单的数据传输还是复杂的对象序列化和反序列化需求,都能得心应手。

    JSON - JAVA 使用方法.docx

    JSON(JavaScript Object Notation)是一种轻量级的数据...总之,JSON是现代Web服务中不可或缺的数据交换格式,Java提供了多种库来支持JSON的处理,包括JSON Lib和Nutz等,使得在Java环境中处理JSON数据变得非常便捷。

    JS和JAVA使用JSON方法解析.doc

    `JSON.stringify()`方法可以将JSON对象转换为字符串,并可选择性地忽略某些属性或格式化输出。 ### Java部分 在Java中,处理JSON通常需要第三方库,如`json-lib`。以下是使用`json-lib`进行JSON操作的步骤: 1. ...

    Json解析工具

    在日常开发工作中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式被广泛使用。为了方便地处理JSON数据,开发者们通常会选择使用各种JSON解析库来简化这一过程。本文将详细介绍几种常用的JSON解析...

Global site tag (gtag.js) - Google Analytics