JSON和Java

本教程将教你如何使用Java编程语言进行编码和解码JSON对象。让我们开始准备开始Java 和 JSON的编程环境。

环境

在开始使用Java编码和解码JSON,将需要安装JSON模块可供选择。在本教程中我下载并安装JSON.simple简单JSON-1.1.1.jar文件的位置,并添加到环境变量CLASSPATH:

JSON和Java实体之间的映射

JSON.simple实体映射从左侧向右侧解码或解析,并映射实体从右侧到左侧编码。

JSONJava
string java.lang.String
number java.lang.Number
true|false ava.lang.Boolean
null null
array java.util.List
object java.util.Map

虽然解码,默认 java.util.List的具体类是具体类 org.json.simple.JSONArray 和默认 java.util.Map 是org.json.simple.JSONObject。

在Java的JSON编码

下面是一个简单的例子来编码JSONObject使用Java的JSON对象的一个子类的java.util.HashMap 无序。如果您需要严格的顺序元素使用方法JSONValue.toJSONString(映射)有序映射实现作为 java.util.LinkedHashMap等。

import org.json.simple.JSONObject;classJsonEncodeDemo{publicstaticvoid main(String[] args){JSONObject obj =newJSONObject();

      obj.put("name","foo");
      obj.put("num",newInteger(100));
      obj.put("balance",newDouble(1000.21));
      obj.put("is_vip",newBoolean(true));System.out.print(obj);}}

虽然上述程序的编译和执行,这将产生以下结果:

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

以下是另一个例子,它显示了使用Java的JSONObject 的 JSON对象流:

import org.json.simple.JSONObject;classJsonEncodeDemo{publicstaticvoid main(String[] args){JSONObject obj =newJSONObject();

      obj.put("name","foo");
      obj.put("num",newInteger(100));
      obj.put("balance",newDouble(1000.21));
      obj.put("is_vip",newBoolean(true));StringWriterout=newStringWriter();
      obj.writeJSONString(out);String jsonText =out.toString();System.out.print(jsonText);}}

虽然上述程序的编译和执行,这将产生以下结果:

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

在Java的JSON解码

下面的例子利用的JSONObject 和JSONArray JSONObject 是一个java.util.Map JSONArray是一个java.util.List,所以可以对其进行访问 Map 和List 的标准操作。

import org.json.simple.JSONObject;import org.json.simple.JSONArray;import org.json.simple.parser.ParseException;import org.json.simple.parser.JSONParser;classJsonDecodeDemo{publicstaticvoid main(String[] args){JSONParser parser=newJSONParser();String s ="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";try{Object obj = parser.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 = parser.parse(s);System.out.println(obj);

         s="[5,]";
         obj = parser.parse(s);System.out.println(obj);

         s="[5,,2]";
         obj = parser.parse(s);System.out.println(obj);}catch(ParseException pe){System.out.println("position: "+ pe.getPosition());System.out.println(pe);}}}

虽然上述程序的编译和执行,这将产生以下结果:

The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]

 

posted @ 2013-09-07 22:21  易百教程  阅读(501)  评论(0编辑  收藏  举报