json学习笔记

json学习笔记
1.需要把json的包源码搞出来,我们就可以测试了。(下载地址)https://github.com/douglascrockford/JSON-javajson学习笔记_第1张图片
2,测试代码如下:

package  shengsiyuan.lxd.json;

import  org.json.JSONArray;
import  org.json.JSONException;
import  org.json.JSONObject;
import  org.junit.Test;

public   class  TestJson
{
    @Test
    
public   void  TestJson01()  throws  JSONException
    {
        String jsonContent 
=   " {'name':'lixiaodaoaaa','age':26} " ;
        JSONObject myJson 
=   new  JSONObject(jsonContent);
        String strName 
=  myJson.getString( " name " ).toString();
        String strAge 
= String.valueOf(myJson.getInt( " age " ));
        System.out.println(strName);
        System.out.println(strAge);
    }
    @Test
    
public   void  TestJson02()  throws  JSONException
    {
        String jsonContent 
= " [{'name':'lixiaodaoaaa','age':22}, "   +
                
" {'name':'lihao','age':26}, "   +
                
" {'name':'libo','age':27}] " ;
        JSONArray myJsonArray 
=   new  JSONArray(jsonContent);
        String strName1  
=  myJsonArray.getJSONObject( 0 ).getString( " name " );
        String strName2  
=  myJsonArray.getJSONObject( 1 ).getString( " name " );
        String strName3  
=  myJsonArray.getJSONObject( 2 ).getString( " name " );
        String strAge1 
=  String.valueOf(myJsonArray.getJSONObject( 0 ).getInt( " age " ));
        String strAge2 
=  String.valueOf(myJsonArray.getJSONObject( 1 ).getInt( " age " ));
        String strAge3 
=  String.valueOf(myJsonArray.getJSONObject( 2 ).getInt( " age " ));
        System.out.println(strName1
+ " .************. " + strAge1);
        System.out.println(strName2
+ " .************. " + strAge2);
        System.out.println(strName3
+ " .************. " + strAge3);
    }
    @Test
    
public   void  TestJson03()  throws  JSONException
    {
        String jsonString 
=   " [{'key':{'name':'lixiaodaoaaa','age':22}}, {'key':{'name':'lihao','age':21}},{'key':{'name':'libo','age':23}}] " ;
        JSONArray myjsonArray 
=   new  JSONArray(jsonString);
        
for ( int  i = 0 ;i < myjsonArray.length();i ++ )
        {
            String strName 
=  myjsonArray.getJSONObject(i).getJSONObject( " key " ).get( " name " ).toString();
            String strAge 
=  String.valueOf(myjsonArray.getJSONObject(i).getJSONObject( " key " ).getInt( " age " ));
            System.out.println(strName
+ " ************************ " + strAge);
        }
    }
}

json学习笔记_第2张图片 


更多信息请访问 java教程网 www.itchm.com

你可能感兴趣的:(json学习笔记)