org.json是一个轻量级的java json库,除了提供基本的json encode/decode的功能外,还提供了很多实用的功能,比如:将map转成json object,将标准的xml字符串转成json object等等。
官方github地址:
https://github.com/stleary/JSON-java
文档链接地址:
http://stleary.github.io/JSON-java/index.html
maven地址:
http://mvnrepository.com/artifact/org.json/json使用例子:
package com.lxl; import java.util.HashMap; import org.json.JSONObject; public class JsonDemo { public static void main(String[] args) { // json encode JSONObject obj = new JSONObject(); obj.put("name","xiaoming"); obj.put("age",20); obj.put("gender",1); String str = obj.toString(); System.out.println(str); // json decode String str2 = "{\"name\":\"xiaoming\",\"age\":20,\"gender\":1}"; JSONObject obj2 = new JSONObject(str2); String name = obj2.optString("name","null"); Integer age = obj2.optInt("age",-1); Integer gender = obj2.optInt("gender",-1); System.out.println(String.format("name=%s,age=%d,gender=%d",name,age,gender)); // map to json object HashMap<String,Object> map = new HashMap<>(); map.put("name","xiaoming"); map.put("age",20); map.put("gender",1); JSONObject obj3 = new JSONObject(map); String str3 = obj3.toString(); System.out.println(str3); } }
运行结果输出:
{"gender":1,"name":"xiaoming","age":20} name=xiaoming,age=20,gender=1 {"gender":1,"age":20}原文链接:https://www.f2er.com/json/288745.html