欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSON for java入门总结

程序员文章站 2022-03-10 08:23:18
...


一、JSON介绍


JSON(JavaScript Object Notation),类似于XML,是一种数据交换格式,比如Java产生了一个数据想要给JavaScript,则除了利用XML外,还可以利用JSON;

JSON相比XML的优势是表达起来很简单;

官网:http://www.json.org/

JSON是AJAX中的X(就是可以取代XML);          ——出自JSON创始人;


注意:JSON并不是一个文档格式,没有*.json的文档,一般JSON格式的文档存在txt中,而XML可以是一个标准;


在线校验JSON结构的网站:http://www.bejson.com/go.html?u=http://www.bejson.com/jsonview2/


二、JSON数据结构


JSON有两种数据结构

(1)Map,也称为对象;{….}

(2)Array;[……]

也就是说所有的JSON对象都是要以这些形式表示;


1.Map


简单的说就是Java中的Map,名称-值对的形式给出,名称和值之间用“:”隔开,两个Map之间用“,”隔开,一般表示形式如下:

{‘key1’:’value1’,’key2’:’value2’}

以下为官网的图:

JSON for java入门总结


2.Array


就是普通意义上的数组,一般形式如下:

[‘arr1’,’arr2’,’arr3’];

以下为官网的图:


JSON for java入门总结


图中的value可以是:


JSON for java入门总结



总结:

(1)JSON的数据结构只有两种;

(2)可以嵌套表示,比如Array中可以嵌套Object等;

(3)记住:Object是以{}表示,Array是以[  ]表示;

 

三、JSON与XML互转示例


前面提到任何的XML都能够转换成JSON包;


1.简单XML


XML格式:

  1. <person>  
  2.     <name>xiazdong</name>  
  3.     <age>20</age>  
  4. </person>  
JSON for java入门总结
<person>
    <name>xiazdong</name>
    <age>20</age>
</person>

JSON格式:

  1. {  
  2.     “name”:”xiazdong”,  
  3.     “age”:20  
  4. }  
JSON for java入门总结
{
    "name":"xiazdong",
    "age":20
}



2.复杂XML


XML格式:

  1. <section>  
  2.     <title>BOOK</title>  
  3.     <signing>  
  4.         <author name=“author-1”/>  
  5.         <book title=“book1” price=11"</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;/</span><span class="tag-name">signing</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">signing</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">author</span><span>&nbsp;</span><span class="attribute">name</span><span>=</span><span class="attribute-value">"author-2"</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">book</span><span>&nbsp;</span><span class="attribute">title</span><span>=</span><span class="attribute-value">"book2"</span><span>&nbsp;</span><span class="attribute">price</span><span>=</span><span class="attribute-value">"22”/>  
  6.     </signing>  
  7. </section>  
JSON for java入门总结
<section>
    <title>BOOK</title>
    <signing>
        <author name="author-1"/>
        <book title="book1" price="$11"/>
    </signing>
    <signing>
        <author name="author-2"/>
        <book title="book2" price="$22"/>
    </signing>
</section>

JSON格式:

  1. ”section”:{  
  2.         “title”:”BOOK”,  
  3.         “signing”:[  
  4.         {  
  5.     <span style=“white-space:pre”>  </span> “author”:  
  6.             {  
  7.                 “name”:”author-1”  
  8.             },  
  9.             “book”:  
  10.             {  
  11.                 “title”:”book1”,  
  12.                 “price”:”11"&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"author":&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"author-2"&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"book":&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"title":"book2",&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"price":"22”  
  13.             }  
  14.         }     
  15. <span style=“white-space:pre”>  </span> ]}  
  16.     }  
JSON for java入门总结
"section":{
        "title":"BOOK",
        "signing":[
        {
       "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
   ]}
    }

注意:XML中的属性也是通过JSON的Map表示;


四、JSON包


如果我们想要使用JSON包,则可以下载JSON包的源代码,并将这些代码添加进Eclipse工程中,即可调用;

如果想要看API文档,可以参见:http://www.JSON.org/java/index.html

JSON包中最常用的两个类就是JSONObject和JSONArray,分别表示两种数据结构;


1.JSONObject代码实例


  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.         JSONObject jsonobj = new JSONObject(“{‘name’:’xiazdong’,’age’:20}”);  
  10.         String name = jsonobj.getString(”name”);  
  11.         int age = jsonobj.getInt(“age”);  
  12.         System.out.println(name+”:”+age);     
  13.           
  14.     }  
  15. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{
        JSONObject jsonobj = new JSONObject("{'name':'xiazdong','age':20}");
        String name = jsonobj.getString("name");
        int age = jsonobj.getInt("age");
        System.out.println(name+":"+age);   

    }
}

2.JSONArray代码实例


JSONArray array = new JSONArray(String str); //将String转为JSONArray

int length = array.length(); //返回Array的长度;

  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.               
  10.         JSONArray jsonarray = new JSONArray(“[{‘name’:’xiazdong’,’age’:20},{‘name’:’xzdong’,’age’:15}]”);  
  11.         for(int i=0;i<jsonarray.length();i++){  
  12.             String name = jsonarray.getJSONObject(i).getString(”name”);  
  13.             int age = jsonarray.getJSONObject(i).getInt(“age”);  
  14.             System.out.println(”name=”+name);  
  15.             System.out.println(”age=”+age);  
  16.         }  
  17.           
  18.     }  
  19. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{

        JSONArray jsonarray = new JSONArray("[{'name':'xiazdong','age':20},{'name':'xzdong','age':15}]");
        for(int i=0;i<jsonarray.length();i++){
            String name = jsonarray.getJSONObject(i).getString("name");
            int age = jsonarray.getJSONObject(i).getInt("age");
            System.out.println("name="+name);
            System.out.println("age="+age);
        }

    }
}

3.嵌套JSONObject和JSONArray代码实例


  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.   
  10.         String str = ”{‘name’:’xiazdong’,’age’:20,’book’:[‘book1’,’book2’]”;  
  11.         JSONObject obj = new JSONObject(str);  
  12.         System.out.println(obj.getJSONArray(”book”).getString(0));  
  13.     }  
  14. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{

        String str = "{'name':'xiazdong','age':20,'book':['book1','book2']";
        JSONObject obj = new JSONObject(str);
        System.out.println(obj.getJSONArray("book").getString(0));
    }
}


4.JSONStringer代码示例


JSONStringer可以用来快速构建一个JSON格式的文本,并转换成String,可以写入文件;

JSONStringer是JSONWriter的子类;

JSONStringer一般通过object().key().value().key().value().endObject()进行构造;

object()表明开始一个对象,即添加{  ;

endObject()表明结束一个对象,即添加 } ;

array()表明开始一个数组,即添加一个 [ ;

endArray()表明结束一个数组,即添加一个 ] ;

key()表示添加一个key;

value()表示添加一个value;

  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONStringer;  
  4.   
  5. public class JsonStringerDemo {  
  6.   
  7.     public static void main(String[] args) throws Exception{  
  8.         JSONStringer stringer = new JSONStringer();  
  9.         String str = stringer.object().key(”name”).value(“xiazdong”).key(“age”).value(20).endObject().toString();  
  10.         System.out.println(str);  
  11.     }  
  12.   
  13. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONStringer;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONStringer stringer = new JSONStringer();
        String str = stringer.object().key("name").value("xiazdong").key("age").value(20).endObject().toString();
        System.out.println(str);
    }

}

复杂JSON格式写入

  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONArray;  
  7. import weibo4j.org.json.JSONObject;  
  8. import weibo4j.org.json.JSONStringer;  
  9. import weibo4j.org.json.JSONTokener;  
  10.   
  11. public class JsonStringerDemo {  
  12.   
  13.     public static void main(String[] args) throws Exception{  
  14.           
  15.         JSONStringer js = new JSONStringer();  
  16.         JSONObject obj2 = new JSONObject();  
  17.         JSONObject obj3 = new JSONObject();  
  18.         JSONObject obj4 = new JSONObject();  
  19.         obj4.put(”title”“book1”).put(“price”11"</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj3.put(<span class="string">"book"</span><span>,&nbsp;obj4);&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj3.put(<span class="string">"author"</span><span>,&nbsp;</span><span class="keyword">new</span><span>&nbsp;JSONObject().put(</span><span class="string">"name"</span><span>,&nbsp;</span><span class="string">"author-1"</span><span>));&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;obj5&nbsp;=&nbsp;<span class="keyword">new</span><span>&nbsp;JSONObject();&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;obj6&nbsp;=&nbsp;<span class="keyword">new</span><span>&nbsp;JSONObject();&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj6.put(<span class="string">"title"</span><span>,&nbsp;</span><span class="string">"book2"</span><span>).put(</span><span class="string">"price"</span><span>,&nbsp;</span><span class="string">"22”);  
  20.         obj5.put(”book”, obj6);  
  21.         obj5.put(”author”new JSONObject().put(“name”“author-2”));  
  22.           
  23.         JSONArray obj7 = new JSONArray();  
  24.         obj7.put(obj3).put(obj5);  
  25.           
  26.           
  27.           
  28.         obj2.put(”title”,“BOOK”);  
  29.         obj2.put(”signing”, obj7);  
  30.           
  31.         js.object().key(”session”).value(obj2).endObject();  
  32.           
  33.         System.out.println(js.toString());  
  34.           
  35.         PrintWriter out = new PrintWriter(new FileOutputStream(1.txt));  
  36.         out.println(js.toString());  
  37.           
  38.       
  39.     }  
  40.   
  41. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONStringer;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{

        JSONStringer js = new JSONStringer();
        JSONObject obj2 = new JSONObject();
        JSONObject obj3 = new JSONObject();
        JSONObject obj4 = new JSONObject();
        obj4.put("title", "book1").put("price", "$11");
        obj3.put("book", obj4);
        obj3.put("author", new JSONObject().put("name", "author-1"));

        JSONObject obj5 = new JSONObject();
        JSONObject obj6 = new JSONObject();
        obj6.put("title", "book2").put("price", "$22");
        obj5.put("book", obj6);
        obj5.put("author", new JSONObject().put("name", "author-2"));

        JSONArray obj7 = new JSONArray();
        obj7.put(obj3).put(obj5);



        obj2.put("title","BOOK");
        obj2.put("signing", obj7);

        js.object().key("session").value(obj2).endObject();

        System.out.println(js.toString());

        PrintWriter out = new PrintWriter(new FileOutputStream(1.txt));
        out.println(js.toString());


    }

}


以上代码生成了如下JSON格式:

  1. {“section”:{  
  2.         ”title”:“BOOK”,  
  3.         ”signing”:[  
  4.         {  
  5.             ”author”:  
  6.             {  
  7.                 ”name”:“author-1”  
  8.             },  
  9.             ”book”:  
  10.             {  
  11.                 ”title”:“book1”,  
  12.                 ”price”:11"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"author"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"name"</span><span>:</span><span class="string">"author-2"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"book"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"title"</span><span>:</span><span class="string">"book2"</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"price"</span><span>:</span><span class="string">"22”  
  13.             }  
  14.         }     
  15.         ]}  
  16.     }  
  17. }  
JSON for java入门总结
{"section":{
        "title":"BOOK",
        "signing":[
        {
            "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
        ]}
    }
}


5.JSONTokener代码示例


JSONTokener是用来读取JSON格式的文件;

JSONObject obj = new JSONObject( new JSONTokener(java.io.Reader));可以从文件中读取一个JSONObject;

JSONArray obj = new JSONArray( new JSONTokener(java.io.Reader)); 可以从文件中读取一个JSONArray;

1.txt

  1. {  
  2.     ’name’:‘xiazdong’,  
  3.     ’book’:[‘book1’,‘book2’]  
  4. }  
JSON for java入门总结
{
    'name':'xiazdong',
    'book':['book1','book2']
}


  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONObject;  
  7. import weibo4j.org.json.JSONTokener;  
  8.   
  9. public class JsonStringerDemo {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File(“1.txt”))));  
  13.         System.out.println(obj.getJSONArray(”book”).getString(1)); //可以读取book2  
  14.     }  
  15.   
  16. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));
        System.out.println(obj.getJSONArray("book").getString(1)); //可以读取book2
    }

}

复杂JSON格式的读取代码:

1.txt

  1. {“section”:{  
  2.         ”title”:“BOOK”,  
  3.         ”signing”:[  
  4.         {  
  5.             ”author”:  
  6.             {  
  7.                 ”name”:“author-1”  
  8.             },  
  9.             ”book”:  
  10.             {  
  11.                 ”title”:“book1”,  
  12.                 ”price”:11"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"author"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"name"</span><span>:</span><span class="string">"author-2"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"book"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"title"</span><span>:</span><span class="string">"book2"</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"price"</span><span>:</span><span class="string">"22”  
  13.             }  
  14.         }     
  15.         ]}  
  16.     }  
  17. }  
JSON for java入门总结
{"section":{
        "title":"BOOK",
        "signing":[
        {
            "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
        ]}
    }
}

  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONObject;  
  7. import weibo4j.org.json.JSONTokener;  
  8.   
  9. public class JsonStringerDemo {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File(“1.txt”))));  
  13.         System.out.println(obj.getJSONObject(”section”).getJSONArray(“signing”).getJSONObject(0).getJSONObject(“author”).getString(“name”)); <span style=“white-space:pre”>     </span>//获取author-1  
  14.     }  
  15.   
  16. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));
        System.out.println(obj.getJSONObject("section").getJSONArray("signing").getJSONObject(0).getJSONObject("author").getString("name"));      //获取author-1
    }

}


总结:


1在Java中JSON格式的String最好用单引号表示;

2.利用JSONObject+JSONTokener能够读取JSON格式文件对象;

3.利用PrintWriter+JSONStringer可以写入JSON文件;

注:由于原本想要试图用JSONWriter写入,但是没有成功;所以只能利用JSONStringer+PrintWriter写入;










 


一、JSON介绍


JSON(JavaScript Object Notation),类似于XML,是一种数据交换格式,比如Java产生了一个数据想要给JavaScript,则除了利用XML外,还可以利用JSON;

JSON相比XML的优势是表达起来很简单;

官网:http://www.json.org/

JSON是AJAX中的X(就是可以取代XML);          ——出自JSON创始人;


注意:JSON并不是一个文档格式,没有*.json的文档,一般JSON格式的文档存在txt中,而XML可以是一个标准;


在线校验JSON结构的网站:http://www.bejson.com/go.html?u=http://www.bejson.com/jsonview2/


二、JSON数据结构


JSON有两种数据结构

(1)Map,也称为对象;{….}

(2)Array;[……]

也就是说所有的JSON对象都是要以这些形式表示;


1.Map


简单的说就是Java中的Map,名称-值对的形式给出,名称和值之间用“:”隔开,两个Map之间用“,”隔开,一般表示形式如下:

{‘key1’:’value1’,’key2’:’value2’}

以下为官网的图:

JSON for java入门总结


2.Array


就是普通意义上的数组,一般形式如下:

[‘arr1’,’arr2’,’arr3’];

以下为官网的图:


JSON for java入门总结


图中的value可以是:


JSON for java入门总结



总结:

(1)JSON的数据结构只有两种;

(2)可以嵌套表示,比如Array中可以嵌套Object等;

(3)记住:Object是以{}表示,Array是以[  ]表示;

 

三、JSON与XML互转示例


前面提到任何的XML都能够转换成JSON包;


1.简单XML


XML格式:

  1. <person>  
  2.     <name>xiazdong</name>  
  3.     <age>20</age>  
  4. </person>  
JSON for java入门总结
<person>
    <name>xiazdong</name>
    <age>20</age>
</person>

JSON格式:

  1. {  
  2.     “name”:”xiazdong”,  
  3.     “age”:20  
  4. }  
JSON for java入门总结
{
    "name":"xiazdong",
    "age":20
}



2.复杂XML


XML格式:

  1. <section>  
  2.     <title>BOOK</title>  
  3.     <signing>  
  4.         <author name=“author-1”/>  
  5.         <book title=“book1” price=11"</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;/</span><span class="tag-name">signing</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">signing</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">author</span><span>&nbsp;</span><span class="attribute">name</span><span>=</span><span class="attribute-value">"author-2"</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">book</span><span>&nbsp;</span><span class="attribute">title</span><span>=</span><span class="attribute-value">"book2"</span><span>&nbsp;</span><span class="attribute">price</span><span>=</span><span class="attribute-value">"22”/>  
  6.     </signing>  
  7. </section>  
JSON for java入门总结
<section>
    <title>BOOK</title>
    <signing>
        <author name="author-1"/>
        <book title="book1" price="$11"/>
    </signing>
    <signing>
        <author name="author-2"/>
        <book title="book2" price="$22"/>
    </signing>
</section>

JSON格式:

  1. ”section”:{  
  2.         “title”:”BOOK”,  
  3.         “signing”:[  
  4.         {  
  5.     <span style=“white-space:pre”>  </span> “author”:  
  6.             {  
  7.                 “name”:”author-1”  
  8.             },  
  9.             “book”:  
  10.             {  
  11.                 “title”:”book1”,  
  12.                 “price”:”11"&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"author":&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"name":"author-2"&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"book":&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"title":"book2",&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"price":"22”  
  13.             }  
  14.         }     
  15. <span style=“white-space:pre”>  </span> ]}  
  16.     }  
JSON for java入门总结
"section":{
        "title":"BOOK",
        "signing":[
        {
       "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
   ]}
    }

注意:XML中的属性也是通过JSON的Map表示;


四、JSON包


如果我们想要使用JSON包,则可以下载JSON包的源代码,并将这些代码添加进Eclipse工程中,即可调用;

如果想要看API文档,可以参见:http://www.JSON.org/java/index.html

JSON包中最常用的两个类就是JSONObject和JSONArray,分别表示两种数据结构;


1.JSONObject代码实例


  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.         JSONObject jsonobj = new JSONObject(“{‘name’:’xiazdong’,’age’:20}”);  
  10.         String name = jsonobj.getString(”name”);  
  11.         int age = jsonobj.getInt(“age”);  
  12.         System.out.println(name+”:”+age);     
  13.           
  14.     }  
  15. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{
        JSONObject jsonobj = new JSONObject("{'name':'xiazdong','age':20}");
        String name = jsonobj.getString("name");
        int age = jsonobj.getInt("age");
        System.out.println(name+":"+age);   

    }
}

2.JSONArray代码实例


JSONArray array = new JSONArray(String str); //将String转为JSONArray

int length = array.length(); //返回Array的长度;

  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.               
  10.         JSONArray jsonarray = new JSONArray(“[{‘name’:’xiazdong’,’age’:20},{‘name’:’xzdong’,’age’:15}]”);  
  11.         for(int i=0;i<jsonarray.length();i++){  
  12.             String name = jsonarray.getJSONObject(i).getString(”name”);  
  13.             int age = jsonarray.getJSONObject(i).getInt(“age”);  
  14.             System.out.println(”name=”+name);  
  15.             System.out.println(”age=”+age);  
  16.         }  
  17.           
  18.     }  
  19. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{

        JSONArray jsonarray = new JSONArray("[{'name':'xiazdong','age':20},{'name':'xzdong','age':15}]");
        for(int i=0;i<jsonarray.length();i++){
            String name = jsonarray.getJSONObject(i).getString("name");
            int age = jsonarray.getJSONObject(i).getInt("age");
            System.out.println("name="+name);
            System.out.println("age="+age);
        }

    }
}

3.嵌套JSONObject和JSONArray代码实例


  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONArray;  
  4. import weibo4j.org.json.JSONObject;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception{  
  9.   
  10.         String str = ”{‘name’:’xiazdong’,’age’:20,’book’:[‘book1’,’book2’]”;  
  11.         JSONObject obj = new JSONObject(str);  
  12.         System.out.println(obj.getJSONArray(”book”).getString(0));  
  13.     }  
  14. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws Exception{

        String str = "{'name':'xiazdong','age':20,'book':['book1','book2']";
        JSONObject obj = new JSONObject(str);
        System.out.println(obj.getJSONArray("book").getString(0));
    }
}


4.JSONStringer代码示例


JSONStringer可以用来快速构建一个JSON格式的文本,并转换成String,可以写入文件;

JSONStringer是JSONWriter的子类;

JSONStringer一般通过object().key().value().key().value().endObject()进行构造;

object()表明开始一个对象,即添加{  ;

endObject()表明结束一个对象,即添加 } ;

array()表明开始一个数组,即添加一个 [ ;

endArray()表明结束一个数组,即添加一个 ] ;

key()表示添加一个key;

value()表示添加一个value;

  1. package com.xiazdong.json;  
  2.   
  3. import weibo4j.org.json.JSONStringer;  
  4.   
  5. public class JsonStringerDemo {  
  6.   
  7.     public static void main(String[] args) throws Exception{  
  8.         JSONStringer stringer = new JSONStringer();  
  9.         String str = stringer.object().key(”name”).value(“xiazdong”).key(“age”).value(20).endObject().toString();  
  10.         System.out.println(str);  
  11.     }  
  12.   
  13. }  
JSON for java入门总结
package com.xiazdong.json;

import weibo4j.org.json.JSONStringer;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONStringer stringer = new JSONStringer();
        String str = stringer.object().key("name").value("xiazdong").key("age").value(20).endObject().toString();
        System.out.println(str);
    }

}

复杂JSON格式写入

  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONArray;  
  7. import weibo4j.org.json.JSONObject;  
  8. import weibo4j.org.json.JSONStringer;  
  9. import weibo4j.org.json.JSONTokener;  
  10.   
  11. public class JsonStringerDemo {  
  12.   
  13.     public static void main(String[] args) throws Exception{  
  14.           
  15.         JSONStringer js = new JSONStringer();  
  16.         JSONObject obj2 = new JSONObject();  
  17.         JSONObject obj3 = new JSONObject();  
  18.         JSONObject obj4 = new JSONObject();  
  19.         obj4.put(”title”“book1”).put(“price”11"</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj3.put(<span class="string">"book"</span><span>,&nbsp;obj4);&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj3.put(<span class="string">"author"</span><span>,&nbsp;</span><span class="keyword">new</span><span>&nbsp;JSONObject().put(</span><span class="string">"name"</span><span>,&nbsp;</span><span class="string">"author-1"</span><span>));&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;obj5&nbsp;=&nbsp;<span class="keyword">new</span><span>&nbsp;JSONObject();&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;obj6&nbsp;=&nbsp;<span class="keyword">new</span><span>&nbsp;JSONObject();&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj6.put(<span class="string">"title"</span><span>,&nbsp;</span><span class="string">"book2"</span><span>).put(</span><span class="string">"price"</span><span>,&nbsp;</span><span class="string">"22”);  
  20.         obj5.put(”book”, obj6);  
  21.         obj5.put(”author”new JSONObject().put(“name”“author-2”));  
  22.           
  23.         JSONArray obj7 = new JSONArray();  
  24.         obj7.put(obj3).put(obj5);  
  25.           
  26.           
  27.           
  28.         obj2.put(”title”,“BOOK”);  
  29.         obj2.put(”signing”, obj7);  
  30.           
  31.         js.object().key(”session”).value(obj2).endObject();  
  32.           
  33.         System.out.println(js.toString());  
  34.           
  35.         PrintWriter out = new PrintWriter(new FileOutputStream(1.txt));  
  36.         out.println(js.toString());  
  37.           
  38.       
  39.     }  
  40.   
  41. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONStringer;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{

        JSONStringer js = new JSONStringer();
        JSONObject obj2 = new JSONObject();
        JSONObject obj3 = new JSONObject();
        JSONObject obj4 = new JSONObject();
        obj4.put("title", "book1").put("price", "$11");
        obj3.put("book", obj4);
        obj3.put("author", new JSONObject().put("name", "author-1"));

        JSONObject obj5 = new JSONObject();
        JSONObject obj6 = new JSONObject();
        obj6.put("title", "book2").put("price", "$22");
        obj5.put("book", obj6);
        obj5.put("author", new JSONObject().put("name", "author-2"));

        JSONArray obj7 = new JSONArray();
        obj7.put(obj3).put(obj5);



        obj2.put("title","BOOK");
        obj2.put("signing", obj7);

        js.object().key("session").value(obj2).endObject();

        System.out.println(js.toString());

        PrintWriter out = new PrintWriter(new FileOutputStream(1.txt));
        out.println(js.toString());


    }

}


以上代码生成了如下JSON格式:

  1. {“section”:{  
  2.         ”title”:“BOOK”,  
  3.         ”signing”:[  
  4.         {  
  5.             ”author”:  
  6.             {  
  7.                 ”name”:“author-1”  
  8.             },  
  9.             ”book”:  
  10.             {  
  11.                 ”title”:“book1”,  
  12.                 ”price”:11"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"author"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"name"</span><span>:</span><span class="string">"author-2"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"book"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"title"</span><span>:</span><span class="string">"book2"</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"price"</span><span>:</span><span class="string">"22”  
  13.             }  
  14.         }     
  15.         ]}  
  16.     }  
  17. }  
JSON for java入门总结
{"section":{
        "title":"BOOK",
        "signing":[
        {
            "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
        ]}
    }
}


5.JSONTokener代码示例


JSONTokener是用来读取JSON格式的文件;

JSONObject obj = new JSONObject( new JSONTokener(java.io.Reader));可以从文件中读取一个JSONObject;

JSONArray obj = new JSONArray( new JSONTokener(java.io.Reader)); 可以从文件中读取一个JSONArray;

1.txt

  1. {  
  2.     ’name’:‘xiazdong’,  
  3.     ’book’:[‘book1’,‘book2’]  
  4. }  
JSON for java入门总结
{
    'name':'xiazdong',
    'book':['book1','book2']
}


  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONObject;  
  7. import weibo4j.org.json.JSONTokener;  
  8.   
  9. public class JsonStringerDemo {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File(“1.txt”))));  
  13.         System.out.println(obj.getJSONArray(”book”).getString(1)); //可以读取book2  
  14.     }  
  15.   
  16. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));
        System.out.println(obj.getJSONArray("book").getString(1)); //可以读取book2
    }

}

复杂JSON格式的读取代码:

1.txt

  1. {“section”:{  
  2.         ”title”:“BOOK”,  
  3.         ”signing”:[  
  4.         {  
  5.             ”author”:  
  6.             {  
  7.                 ”name”:“author-1”  
  8.             },  
  9.             ”book”:  
  10.             {  
  11.                 ”title”:“book1”,  
  12.                 ”price”:11"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"author"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"name"</span><span>:</span><span class="string">"author-2"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"book"</span><span>:&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"title"</span><span>:</span><span class="string">"book2"</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">"price"</span><span>:</span><span class="string">"22”  
  13.             }  
  14.         }     
  15.         ]}  
  16.     }  
  17. }  
JSON for java入门总结
{"section":{
        "title":"BOOK",
        "signing":[
        {
            "author":
            {
                "name":"author-1"
            },
            "book":
            {
                "title":"book1",
                "price":"$11"
            }
        },
        {
            "author":
            {
                "name":"author-2"
            },
            "book":
            {
                "title":"book2",
                "price":"$22"
            }
        }   
        ]}
    }
}

  1. package com.xiazdong.json;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileReader;  
  5.   
  6. import weibo4j.org.json.JSONObject;  
  7. import weibo4j.org.json.JSONTokener;  
  8.   
  9. public class JsonStringerDemo {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File(“1.txt”))));  
  13.         System.out.println(obj.getJSONObject(”section”).getJSONArray(“signing”).getJSONObject(0).getJSONObject(“author”).getString(“name”)); <span style=“white-space:pre”>     </span>//获取author-1  
  14.     }  
  15.   
  16. }  
JSON for java入门总结
package com.xiazdong.json;

import java.io.File;
import java.io.FileReader;

import weibo4j.org.json.JSONObject;
import weibo4j.org.json.JSONTokener;

public class JsonStringerDemo {

    public static void main(String[] args) throws Exception{
        JSONObject obj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt"))));
        System.out.println(obj.getJSONObject("section").getJSONArray("signing").getJSONObject(0).getJSONObject("author").getString("name"));      //获取author-1
    }

}


总结:


1在Java中JSON格式的String最好用单引号表示;

2.利用JSONObject+JSONTokener能够读取JSON格式文件对象;

3.利用PrintWriter+JSONStringer可以写入JSON文件;

注:由于原本想要试图用JSONWriter写入,但是没有成功;所以只能利用JSONStringer+PrintWriter写入;










 

相关标签: java json