您的位置:首页 > Web前端 > JavaScript

JSON的一点自己的理解

2012-02-13 15:07 323 查看
今天由于帮朋友用ajax实现autocomplete的功能,用到json 然后就看了下 有点理解 写下来以防忘记

里面很多是查资料查出来的,然后附带自己的整理和理解

java中操作json:

1:创建JSONObject

private static JSONObject createJSONObject(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","Ouvidia");
jsonObject.put("sex", "M");
return jsonObject;
}



上面是最简单的创建jsonObject的方法

2:JsonConfig 的介绍

JsonConfig :

Utility class that helps configuring the serialization process.

创建JSONObject时可以使用JsonConfig 进行配置

查看JsonConfig 时感觉其中有两个方法比较实用(暂时只用了其中这两个方法)都是进行过滤掉不需要的属性

1)setExcludes方法

public void setExcludes(String[] excludes)
Sets the excludes to use.
Will set default value ([]) if null.
[Java -> JSON]

例子:

public  void testExcludeProperites() {
String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[] { "double", "boolean" });
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str, jsonConfig);
System.out.println(JSONObject.toString());
}

2)由于上面的方法只是配置了需要排除的属性 但有时我们的需求是取出beans的某些属性进行转换成json如果用上面的方法就会有点复杂(利用反射机制应该可以做)

接下的方法就是setJavaPropertyFilter

setJavaPropertyFilter
public void setJavaPropertyFilter(PropertyFilter javaPropertyFilter)Sets a property filter used when serializing to Java.
[JSON -> Java]

Parameters:
javaPropertyFilter - the property filter


这里用到了PropertyFilter属性过滤

它是一个接口 只有一个方法:

boolean apply(Object source,
String name,
Object value)Parameters:
source - the owner of the property
name - the name of the property
value - the value of the property
Returns:
true if the property will be filtered out, false otherwise


我们可以实现PropertyFilter 重写apply方法 进行设置需要过滤的方法

protected PropertyFilter filter(final String [] excludes)
{
return new PropertyFilter()
{
public boolean apply(Object arg0, String arg1, Object arg2)
{
boolean bool = false;
for (int i = 0; i < excludes.length; i++)
{
if (arg1.equals(excludes[i]))
{
bool = true;
}
else
{
bool = false;
}
}
return bool;
}
};
}


3:有了2的只是我们就可以轻松用java操作json了

JSONObject jsonObject=JSONObject.fromObject(obj);
//jsonArray
JSONArray jsonArray=JSONArray.fromObject(obj);

for (int i = 0; i < array.size(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
}




然后就是JsonObject转换成javabean了

JSONObject.toBean(jsonObject, clazz)


4:将获得的json传递至页面

response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObject.toString());


5:json可以不用值对形式出现

JSONArray jso=new JSONArray();
jso.add(0, "test1");
jso.add(1,"test2");
System.out.println(jso.toString());


这样得到的json对象为["test1","test2"]

前台通过ajax设置type为json可以读取数据

直接通过数组形式读取内容




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: