- 教程链接(json-smple1.1.1.jar文件)
- 链接:http://pan.baidu.com/s/1qXPbYHm 密码:v0f0
- 如何使用java编程语言编码和解码JSON
- 首先准备环境以便针对JSON进行java编程
- 下载jsonsimple-1.1.1.jar文件
- 把jar文件的路径添加到classpath环境变量当中
- JSON和java实体的映射
- JSON.simple实体映射从左侧到右侧为解码或者解析,实体映射从右侧到左侧为编码
- 解码时,
- java.util.List的默认具体类是org.simple.JSONArray,
- java.util.Map的默认具体类是org.simple.JSONObject
- 在java中编码JSON
- 使用java.util.HashMap的子类JSONObject编码一个JSON对象,这里并没有提供顺序
- 如果需要严格的元素顺序,可以使用JSONValue.toJSONString(map)方法的有序映射实现,比如java.util.LinkedHashMap.
- 运行上面的程序,将会出现下面的结果
- 下面是另外一个例子,使用java JSONObject展示了JSON对象流
- 运行上面的程序,将会显示下面的结果
- 在java程序当中解码JSON
- 例子当中使用了JSONObject和JSONArray,其中,
- JSONObejct就是java.util.Map
- JSONArray就是java.util.List
- 因此,我们可以使用Map或者是List的标准操作来操作来访问他们
- 运行上面的程序,显示结果如下
package jlu.yangzs.json;
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
package jlu.yangzs.json;
import java.io.IOException;
import java.io.StringWriter;
import org.json.simple.JSONObject;
public class JsonTest {
public static void main(String[] args) throws IOException {
JSONObject jsonObejct=new JSONObject();
jsonObejct.put("name", "foo");
jsonObejct.put("num",new Integer(100));
jsonObejct.put("balance", new Double(100.21));
jsonObejct.put("is_vip", new Boolean(true));
//下面两句代码比较关键
StringWriter out=new StringWriter();
jsonObejct.writeJSONString(out);
String jsonText=out.toString();
System.out.println(jsonText);
}
}
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
package jlu.yangzs.jsondecode;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonDecodeDemo {
public static void main(String[] args) {
JSONParser parser=new JSONParser();
String s="[0,{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}]";
try {
Object obj=parser.parse(s);
JSONArray jsonArray=(JSONArray)obj;
System.out.println("the 2nd element of array:");
System.out.println(jsonArray.get(1));
System.out.println();
JSONObject jsonObj=(JSONObject)jsonArray.get(1);
System.out.println("Field "1"");
System.out.println(jsonObj.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 e) {
e.printStackTrace();
}
}
}
the 2nd element of array:
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
Field "1"
null
{}
[5]
[5,2]