json-smart 使用示例

json是一种通用的数据格式。相比与protocal buffer、thrift等数据格式,json具有可读性强(文本)、天生具备良好的扩展性(随意增减字段)等优良特点,利用json作为通讯协议,开发效率更高。当然相较于二进制协议,文本更耗带宽。

json和HTTP协议都是基于文本的,天生的一对。面对多终端的未来,使用Json和HTTP作为前端架构的基础将成为开发趋势。

简介

json-smart官方主页:https://code.google.com/p/json-smart/

特性:https://code.google.com/p/json-smart/wiki/FeaturesTests

性能评测:https://code.google.com/p/json-smart/wiki/Benchmark

Json-smart-API:  http://www.jarvana.com/jarvana/view/net/minidev/json-smart/1.0.9/json-smart-1.0.9-javadoc.jar!/net/minidev/json/package-summary.html

javadoc: https://github.com/u2waremanager/maven-repository/blob/master/net/minidev/json-smart/1.1.1/json-smart-1.1.1-javadoc.jar

使用示例

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONStyle;
import net.minidev.json.parser.ParseException; import java.io.UnsupportedEncodingException;
import java.util.*; /*
* Home page: http://code.google.com/p/json-smart/
*
* compiler: javac -cp json-smart-1.1.1.jar JsonSmartTest.java
*
* Run: java -cp ./:json-smart-1.1.1.jar JsonSmartTest
*
*/ public class JsonSmartTest { //1. String <==> JsonObject
public static void DecodingTest() throws ParseException {
System.out.println("=======decode======="); String s="[0,{'1':{'2':{'3':{'4':[5,{'6':7}]}}}}]";
Object obj=JSONValue.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println(); JSONObject obj2=(JSONObject)array.get(1);
System.out.println("======field \"1\"==========");
System.out.println(obj2.get("1")); s="{}";
obj=JSONValue.parse(s);
System.out.println(obj); s="{\"key\":\"Value\"}";
// JSONValue.parseStrict()
// can be use to be sure that the input is wellformed
obj=JSONValue.parseStrict(s);
JSONObject obj3=(JSONObject)obj;
System.out.println("====== Object content ======");
System.out.println(obj3.get("key"));
System.out.println(); } public static void EncodingTest() {
System.out.println("=======EncodingTest======="); // Json Object is an HashMap<String, Object> extends
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", 100);
obj.put("balance", 1000.21);
obj.put("is_vip", true);
obj.put("nickname",null); System.out.println("Standard RFC4627 JSON");
System.out.println(obj.toJSONString()); System.out.println("Compacted JSON Value");
System.out.println(obj.toJSONString(JSONStyle.MAX_COMPRESS)); // if obj is an common map you can use: System.out.println("Standard RFC4627 JSON");
System.out.println(JSONValue.toJSONString(obj)); System.out.println("Compacted JSON Value");
System.out.println(JSONValue.toJSONString(obj, JSONStyle.MAX_COMPRESS)); } public static void EncodingTest2() {
System.out.println("=======EncodingTest2======="); // Json Object is an HashMap<String, Object> extends
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", 100);
obj.put("balance", 1000.21);
obj.put("is_vip", true);
obj.put("nickname",null); //Output Compressed json
Object value = obj;
String com_json = JSONValue.toJSONString(value, JSONStyle.MAX_COMPRESS);
String json = JSONValue.toJSONString(value, JSONStyle.NO_COMPRESS); System.out.println("Compacted JSON Value");
System.out.println(com_json);
System.out.println("From RFC4627 JSON String: " + JSONValue.compress(json));
System.out.println("From Compacted JSON String: " + JSONValue.compress(com_json)); System.out.println("Standard RFC4627 JSON Value");
System.out.println(json);
System.out.println("From RFC4627 JSON String: " + JSONValue.uncompress(json));
System.out.println("From Compacted JSON String: " + JSONValue.uncompress(com_json)); //from compress json string
System.out.println("From compress json string(JSONObject)");
Object obj2=JSONValue.parse(com_json);
System.out.println(JSONValue.toJSONString(obj2, JSONStyle.NO_COMPRESS));
System.out.println(JSONValue.toJSONString(obj2, JSONStyle.MAX_COMPRESS));
} //2. Java Struct <==> JsonSmart object
public class Person {
String name;
int age;
boolean single;
long mobile; public String getName(){
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public boolean getSingle() {
return this.single;
}
public void setSingle(boolean single) {
this.single = single;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
} public class JSONDomain { // for convert struct <==> json
public Object result = new JSONObject(); public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
} public void Struct2JsonObject() {
System.out.println("========Struct2JsonObject======="); Person person = new Person();
person.setName("json smart");
person.setAge(13);
person.setMobile(20130808); Person person2 = new Person();
person2.setName("test");
person2.setAge(123);
person2.setMobile(888666); List<Person> array = new ArrayList<Person>();
array.add(person);
array.add(person2); //1. struct <==> JsonObject
JSONObject obj = new JSONObject();
//obj = (Object)person; // compiler error!
// way 1:
JSONDomain data = new JSONDomain(); // for convert
data.setResult(person);
// obj = (JSONObject)data.getResult(); // run error: ClassCastException
obj.put("person", data.getResult());
System.out.println(JSONValue.toJSONString(obj)); // way 2:
obj.put("person", array.get(1));
System.out.println(JSONValue.toJSONString(obj)); //2. Container <==> JsonObject
JSONArray jsonArray = new JSONArray();
jsonArray.add(person);
jsonArray.add(person2);
JSONObject result = new JSONObject();
result.put("persons", jsonArray);
System.out.println(JSONValue.toJSONString(result));
} //3. JsonSmartSerializationTest
public static Map<String, Object> testBytes2Map(byte[] bytes) {
Map<String, Object> map = null;
try {
map = (Map<String, Object>) JSONValue.parseStrict((new String(bytes, "UTF-8")));
} catch (ParseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return map;
} // JsonSmartSerializationTest
public static byte[] testMap2Bytes(Map<String, Object> map) {
String str = JSONObject.toJSONString(map);
byte[] result = null;
try {
result = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
} public static void main(String[] args) throws Exception {
DecodingTest(); EncodingTest(); EncodingTest2(); JsonSmartTest test = new JsonSmartTest();
test.Struct2JsonObject(); }
}

参考

Java序列化与JSON序列化大比拼

Java序列化与JSON序列化大比拼2

多终端的前端架构选择

作者:zhenjing.chen 
出处:http://www.cnblogs.com/zhenjing/ 
未注明转载的文章,版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

json-smart 使用示例的更多相关文章

  1. Salesforce Apex 使用JSON数据的示例程序

    本文介绍了一个在Salesforce Apex中使用JSON数据的示例程序, 该示例程序由以下几部分组成: 1) Album.cls, 定了了封装相关字段的数据Model类 2) RestClient ...

  2. python中json的操作示例

    先上一段示例 # -*- coding: cp936 -*- import json #构造一个示例数据,并打印成易读样式 j = {} j["userName"]="a ...

  3. JSON 下 -- jansson 示例

    JSON 下 —— jansson 示例 参考网址: jansson 库的下载: http://www.digip.org/jansson/ 安装jansson 步骤: http://blog.csd ...

  4. qt qml ajax 获取 json 天气数据示例

    依赖ajax.js类库,以下代码很简单的实现了获取天气json数据并展示的任务 [TestAjax.qml] import QtQuick 2.0 import "ajax.js" ...

  5. Jackson序列化和反序列化Json数据完整示例

    Jackson序列化和反序列化Json数据 Web技术发展的今天,Json和XML已经成为了web数据的事实标准,然而这种格式化的数据手工解析又非常麻烦,软件工程界永远不缺少工具,每当有需求的时候就会 ...

  6. Json -- 语法和示例,javascript 解析Json

    1. 语法 JSON(JavaScriptObject Notation)一种简单的数据格式,比xml更轻巧.JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不 ...

  7. nodejs - json序列化&反序列化示例

    // demo-json.js var obj = { "name": "LiLi", "age": 22, "sex" ...

  8. android json 解析 简单示例

    1 下面是一个简单的json 解析的demo,废话不多说,直接上代码 package com.sky.gallery; import java.io.ByteArrayOutputStream; im ...

  9. python+requests+json 接口测试思路示例

    实际项目中用python脚本实现接口测试的步骤: 1 发送请求,获取响应  >>2 提取响应里的数据,对数据进行必要的处理  >>3 断言响应数据是否与预期一致 以豆瓣接口为例 ...

  10. jQuery中使用Ajax获取JSON格式数据示例代码

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.JSONM文件中包含了关于“名称”和“值”的信息.有时候我们需要读取JSON格式的数据文件,在jQuery中 ...

随机推荐

  1. CSDN专家吐槽实录

    今天打开CSDN发现界面上的几个图标发生了变化,一个小小的变化,却引起了诸多CSDN专家对CSDN社区未来发展的思考,我特意从群里讲对话黏贴出来,希望各位能给予积极评价和建议. 你已经是群成员了,和大 ...

  2. 我在Yahoo与ATS 九死一生的故事

    我在Yahoo与ATS 九死一生的故事 http://www.sunchangming.com/blog/post/4667.html 去年9月,我去Yahoo后领导交给我的第一件事,就是把Yahoo ...

  3. cfs

    转自:http://www.cnblogs.com/openix/p/3254394.html 下文中对于红黑树或链表组织的就绪队列,统称为用队列组织的就绪队列.                    ...

  4. c# p2p 穿透(源码加密)

    http://blog.oraycn.com/ESFramework_Demo_P2P.aspx 测试,完全OK!  我很喜欢这个.可以源码是加密的!我希望实现 web 版本的p2p视频观看,aehy ...

  5. PyCharm 使用简介

    PyCharm 使用简介 最近由于项目需要,领导要求使用python以方便扩展,没有办法,赶鸭子上架花了2天时间翻完了python的初级教程然后就开始写代码.有一款好的IDE可以帮助我快速上手一门新语 ...

  6. API帮助页面

    ASP.NET Web API 2:创建API帮助页面        当你新建了一个web API服务之后,再建一个API帮助页面是很有好处的,这样其他开发人员就会很清楚地知道如何调用你的API接口. ...

  7. iOS开发的一些奇巧淫技2

    能不能只用一个pan手势来代替UISwipegesture的各个方向? - (void)pan:(UIPanGestureRecognizer *)sender { typedef NS_ENUM(N ...

  8. Coreseek:索引和检测的第二步骤施工

    1,非常索引easy,代码行 g:/service/coreseek/bin/indexer -c g:/service/coreseek/etc/csft_mysql.conf   person 在 ...

  9. MySQL中group_concat函数-和group by配合使用

    MySQL中group_concat函数 完整的语法如下: group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔 ...

  10. POJ 2560 Freckles Prime问题解决算法

    这个问题正在寻求最小生成树. 给定节点的坐标,那么我们需要根据各个点之间的这些坐标来计算距离. 除了这是标准的Prime算法的,能源利用Prime基本上,你可以使用Kruskal. 经典的算法必须填写 ...