Your rating : |
|
|
Collect this experience |
These two are the API of the official website
Jsonobject API
Jsonarray API
There are all the methods of these two classes, is a rare good material oh ~
With the above API, we look at this code, you will have a great harvest ~
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.*; /** * * @author derek */ public class JavaTest { public static void main(String[] args){ JSONObject obj= new JSONObject(); obj.put( "derek" , "23" ); obj.put( "dad" , "49" ); obj.put( "mom" , "45" ); System.out.println( "通过构造器的方式创建的JSONObject对象:" +obj); Map<String,String> map= new LinkedHashMap<>(); map.put( "derek" , "23" ); map.put( "dad" , "49" ); map.put( "mom" , "45" ); System.out.println( "通过fromObject方法将map对象转换为JSONObject对象:" +JSONObject.fromObject(map)); JSONArray arr= new JSONArray(); arr.add( 0 , "derek" ); arr.add( 1 , "dad" ); arr.add( 2 , "mom" ); System.out.println( "通过构造器的方式创建的JSONArray:" +arr); ArrayList<String> list= new ArrayList<>(); list.add( "derek" ); list.add( "dad" ); list.add( "mom" ); System.out.println( "通过fromObject方法将Arraylist对象转换为JSONArray对象:" +JSONArray.fromObject(list)); System.out.println( "将HashMap对象通过fromObject方法转换为JSONArray对象" +JSONArray.fromObject(map)); String str= "{\"derek\":23,\"dad\":49,\"mom\":45}" ; System.out.println( "解析之后的JSON对象:" +JSONObject.fromObject(str)); //遍历输出 Iterator<String> it=obj.keys(); while (it.hasNext()){ String key=it.next(); System.out.println(key+ ":" +obj.get(key)); } } } |
The results of the operation are as follows:
Jsonobject object created by the constructor: {"Derek": "All", "Dad": "$", "Mom": "45"}
Convert the Map object to a Jsonobject object through the Fromobject method: {"Derek": "Zero", "Dad": "$", "Mom": "45"}
Jsonarray:["Derek", "Dad", "Mom" created by the constructor
Convert ArrayList objects to Jsonarray objects by the Fromobject method: ["Derek", "Dad", "Mom"]
Convert the HashMap object through the Fromobject method to the Jsonarray object [{"Derek": "Zero", "Dad": "$", "Mom": "45"}]
Parsed JSON object: {"Derek": $, "Dad": $, "Mom": 45}
Derek:23
dad:49
Mom:45
Go Jsonobject,jsonarray User Manual