json-smart 使用示例(推荐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 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 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 array = new ArrayList();
        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 testBytes2Map(byte[] bytes) {
        Map map = null;
        try {
            map = (Map) 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 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 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());
    }
}

复制代码

参考


多终端的前端架构选择


本文转自 zhenjing 博客园博客,原文链接:http://www.cnblogs.com/zhenjing/p/json-smart.html   ,如需转载请自行联系原作者


相关文章
|
6月前
|
JSON API 数据格式
淘宝商品评论API接口,json数据示例参考
淘宝开放平台提供了多种API接口来获取商品评论数据,其中taobao.item.reviews.get是一个常用的接口,用于获取指定商品的评论信息。以下是关于该接口的详细介绍和使用方法:
|
9月前
|
XML JSON API
淘宝商品详情API的调用流程(python请求示例以及json数据示例返回参考)
JSON数据示例:需要提供一个结构化的示例,展示商品详情可能包含的字段,如商品标题、价格、库存、描述、图片链接、卖家信息等。考虑到稳定性,示例应基于淘宝开放平台的标准响应格式。
|
9月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 &quot;&quot;,Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
453 0
|
11月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
9月前
|
JSON 监控 API
python语言采集淘宝商品详情数据,json数据示例返回
通过淘宝开放平台的API接口,开发者可以轻松获取商品详情数据,并利用这些数据进行商品分析、价格监控、库存管理等操作。本文提供的示例代码和JSON数据解析方法,可以帮助您快速上手淘宝商品数据的采集与处理。
|
9月前
|
存储 JSON API
淘宝商品详情API接口概述与JSON数据示例
淘宝商品详情API是淘宝开放平台提供的核心接口之一,为开发者提供了获取商品深度信息的能力。以下是技术细节和示例:
|
11月前
|
JSON 缓存 API
解析电商商品详情API接口系列,json数据示例参考
电商商品详情API接口是电商平台的重要组成部分,提供了商品的详细信息,支持用户进行商品浏览和购买决策。通过合理的API设计和优化,可以提升系统性能和用户体验。希望本文的解析和示例能够为开发者提供参考,帮助构建高效、可靠的电商系统。
418 12
|
10月前
|
JSON API 数据格式
淘宝商品评论数据API接口详解及JSON示例返回
淘宝商品评论数据API接口是淘宝开放平台提供的一项服务,旨在帮助开发者通过编程方式获取淘宝商品的评论数据。这些数据包括评论内容、评论时间、评论者信息、评分等,对于电商分析、用户行为研究、竞品分析等领域都具有极高的价值。
|
JSON API 数据格式
Amazon商品详情API,json数据格式示例参考
亚马逊商品详情API接口返回的JSON数据格式通常包含丰富的商品信息,以下是一个简化的JSON数据格式示例参考
|
JSON API 数据安全/隐私保护
拍立淘按图搜索API接口返回数据的JSON格式示例
拍立淘按图搜索API接口允许用户通过上传图片来搜索相似的商品,该接口返回的通常是一个JSON格式的响应,其中包含了与上传图片相似的商品信息。以下是一个基于淘宝平台的拍立淘按图搜索API接口返回数据的JSON格式示例,同时提供对其关键字段的解释