关于json库,请使用fastjson,这是我用过的最好用的json库!

地址:https://github.com/alibaba/fastjson

=======================================================

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(); }
}

解析文件示例

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.*; import java.lang.StringBuffer; import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException; /*
* Home page: http://code.google.com/p/json-smart/
*
* compiler: javac -cp json-smart-1.1.1.jar JsonTool.java
*
* Run: java -cp ./:json-smart-1.1.1.jar JsonTool
*
*/ public class JsonTool { //1. String <==> JsonObject
public static void ParseData(String data) throws ParseException {
System.out.println("=======decode======="); // s="{\"key\":\"Value\"}";
Object obj = JSONValue.parseStrict(data);
JSONObject obj3 = (JSONObject)obj; System.out.println(obj3.get("data"));
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 main(String[] args) throws Exception { if( args.length < 1) {
System.out.println("Usage: JsonTool file");
System.exit(-1);
} String file = args[0];
System.out.println(file); StringBuffer strBuffer = new StringBuffer();
InputStreamReader inputReader = null;
BufferedReader bufferReader = null;
OutputStream outputStream = null;
try
{
InputStream inputStream = new FileInputStream(file);
inputReader = new InputStreamReader(inputStream);
bufferReader = new BufferedReader(inputReader); // 读取一行
String line = null; while ((line = bufferReader.readLine()) != null)
{
strBuffer.append(line);
} }
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
// OtherUtilAPI.closeAll(outputStream, bufferReader, inputReader);
} //System.out.println(strBuffer.toString());
//System.out.println("\n"); ParseData(strBuffer.toString());
}
}

参考

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

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

多终端的前端架构选择

json-smart 使用示例(推荐fastjson)的更多相关文章

  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. Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例

    Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例 继上篇json解析,我用了原生的json解析,但是在有些情况下我们不得不承认,一些优秀的json解析框架确实十分的 ...

  4. Json解析教程(四.FastJson 的使用)

    简介 Fastjson是一个Java语言编写的高性能功能完善的JSON库. 高性能 fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库,包括曾经号称最快的jackson. ...

  5. Spring Boot返回json数据及完美使用FastJson解析Json数据

     Spring Boot返回json数据 视频地址:http://www.iqiyi.com/w_19rubxzsr5.html 博文参考:https://blog.csdn.net/linxingl ...

  6. JSON工具类库: alibaba/fastjson 使用记录

    JSON工具类库: alibaba/fastjson 使用记录 一.了解JSON JSON标准规范中文文档: http://www.json.org/json-zh.html 最佳实践:http:// ...

  7. JSON 下 -- jansson 示例

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

  8. JSON 解析 (三)—— FastJSON与Jackson比较

    一.方便性与性能 调用方便性而言: FastJSON提供了大量静态方法,调用简洁方便 Jackson须实例化类,调用相对繁琐,可通过封装成JSON工具类简化调用 性能而言: FastJSON反序列化的 ...

  9. spring boot2 修改默认json解析器Jackson为fastjson

    0.前言 fastjson是阿里出的,尽管近年fasjson爆出过几次严重漏洞,但是平心而论,fastjson的性能的确很有优势,尤其是大数据量时的性能优势,所以fastjson依然是我们的首选:sp ...

随机推荐

  1. iazq更新网址

    [版本:1.1] [介绍:哈哈(ಡωಡ)hiahiahia 新版软件试试去和哥哥刚放学噢噢噢天然呆翡翠城] [链接:http://info.3g.qq.com/g/s?aid=index&g_ ...

  2. java中获取路径的几种方式

    总是忘记, 备份一下,方便下次用. 第一种: File directory = new File("");//参数为空 String courseFile = directory. ...

  3. 一个Angular模块中可以声明哪些组件?

    一个Angular模块中可以声明哪些组件? (1) controller        控制器 (2) directive                指令 (3) function         ...

  4. Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码

    本问主要介绍asp.net的身份验证机制及asp.net MVC拦截器在项目中的运用.现在让我们来模拟一个简单的流程:用户登录>权限验证>异常处理 1.用户登录 验证用户是否登录成功步骤直 ...

  5. JS实现的简单横向伸展二级菜单

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. ORACLE 自动增长通过封装函数,方便调用

    好的编程习惯,是一个很有必要的过程.好的编程习惯,可以因人而异,但是简单地.基本地代码级别的就那些:写注释.合理的缩进.换行.变量命名等. 对我们程序员来说,大部分时间都对着电脑,在对着电脑的大部分时 ...

  7. window.innerWidth、document.body.clientWidth和html的大小的区别

    首先,我们知道document.body指向的就是body元素,如此,我们就可以以document.body来获取body的大小.何以知之?如下代码: var body = document.quer ...

  8. HDU 1575

    Tr A Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  9. iOS 利用webView加载html代码,在代理中获取html页面的链接时出现的问题

    getDetailWebview.loadHTMLString(webViewData as String, baseURL:NSURL(string: "\(ProBaseWeb)&quo ...

  10. Windows 商店应用中使用 Office 365 API Tools

    本篇我们介绍一个API 工具,用于在 Windows Store App 中使用 Office 365 API. 首先来说一下本文的背景: 使用 SharePoint 做过开发的同学们应该都知道,Sh ...