服務端提供的JSON資料介面與使用者端接收解析JSON資料

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   sp   

JSON格式的服務介面: http://www.cnblogs.com/jameslif/p/4119184.html

首先來瞭解下JSON格式解析

json結構的格式就是若干個 鍵/值(key, value) 對的集合,該集合可以理解為字典(Dictionary),每個 鍵/值 對可以理解成一個對象(Object)。 鍵/值 對中的 鍵(key) 一般是 一個string,值(value)可以是string、double、int等基本類型,也可以嵌套一個 鍵/值 對,也可以是一個數組,數組裡面的資料的類型可以是基本類型,或者 鍵/值 對。可以看出 鍵/值 本來沒什麼,只是嵌套得多了就會覺得混亂,下面舉個具體的例子來說明。註:該代碼只是用來舉例說明,並不能正確運行。

1 var testJson = { 2 "Name" : "奧巴馬" , 3 "ByName" : ["小奧","小巴","小馬"], 4 "Education" : { 5 "GradeSchool" : "華盛頓第一小學", 6 "MiddleSchool" : ["華盛頓第一初中" , "華盛頓第一高中"], 7 "University" : { 8 "Name" : "哈佛大學", 9 "Specialty" : ["軟體工程","會計"] 10 } 11 } 12 }

變數testJson就是一個json對象,testJson對象包括三個 鍵/值 對。

第一個 鍵/值 對: 鍵(key)是"Name“ ,其對應的值(value)是 "奧巴馬" ,即 testJson["Name"]  == "奧巴馬"

第二個 鍵/值 對: 鍵 是 "ByName" ,值是一個數組,是一個string集合。有必要的話,數組裡面的元素也可以是 鍵/值 對。

第三個 鍵/值 對: 鍵 是 "Education",值是一個 Json對像,該json對象包括三個 鍵/值 對,這就是嵌套了。。。

總結:json對象就是若干個 鍵/值 對的集合,鍵是string,值可以是基本類型,或者嵌套一個Json對象,或者是一個數組(數組裡的元素可以是基本類型,也可以是json對象,可以繼續嵌套)。

擷取名字:testJson["Name"]

擷取第一個別名:testJson["ByName"][0] 。testJson的 鍵"ByName" 對應的值 是一個string數組

擷取小學名字: testJson["Education"]["GradeSchool"] , 擷取大學主修專業:testJson["Education"]["University"]["Specialty"][0]

 

下面舉個執行個體:

定義一個符合json格式要求的字串:

string testJson = "{\"Name\" : \"奧巴馬\",\"ByName\" : [\"小奧\",\"小巴\",\"小馬\"],\"Education\":{\"GradeSchool\" : \"華盛頓第一小學\",\"MiddleSchool\" : [\"華盛頓第一初中\" , \"華盛頓第一高中\"], \"University\" :{ \"Name\" : \"哈佛大學\", \"Specialty\" : [\"軟體工程\",\"會計\"]}}}";             

然後需要用該字串作為參數new 一個 JsonObject對象。微軟內建的類庫 System.Json ,然後添加命名空間 using System.Json;

主要代碼就一句:JsonObject js = JsonObject.Parse(testJson); 用字串testJson 作為參數new 一個 JsonObject 對象。通過監視我們可以看到js裡面的內容和預料的一樣,通過下面這幅圖你應該可琢磨出很多東西來吧

 

額外插一句:js["Education"]["University"]["Specialty"] 的內容是 {[  "軟體工程",  "會計"]},

但js["Education"]["University"]["Specialty"].Contains( "軟體工程") 的值 是false。原因自己琢磨

 

通過Servlet建立服務端JSON資料

服務端提供JSON資料介面:http://192.168.0.129:8080/JSONInterface/JsonServlet

 
package JsonManager;import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;/** * JSONObject 建立一個JSON對象並out.write(); * @author Dana·Li */public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); //解決中文亂碼問題 PrintWriter out = response.getWriter(); Map map = new HashMap(); map.put("name", "Dana、Li"); map.put("age", new Integer(22)); map.put("Provinces", new String("廣東省")); map.put("citiy", new String("珠海市")); map.put("Master", new String("C、C++、Linux、Java")); JSONObject json = JSONObject.fromObject(map); out.write(json.toString()); out.flush(); out.close(); }}
 

開啟服務查看是否已經開啟~

用戶端調用介面解析JSON資料

 
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.URL;import java.net.URLConnection;/** * 接收服務端Json資料 * @author Dana·Li */public class GetJsonInterfaceInfo{ private static String urlPath="http://192.168.0.129:8080/JSONInterface/JsonServlet"; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //ServerFactory.getServer(8080).start(); //列出未經處理資料 StringBuilder json = new StringBuilder(); URL oracle = new URL(GetJsonInterfaceInfo.urlPath); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8")); String inputLine = null; while ( (inputLine = in.readLine()) != null){ json.append(inputLine); } in.close(); String Strjson=json.toString(); System.out.println("未經處理資料:"); System.out.println(Strjson.toString()); }}

服務端提供的JSON資料介面與使用者端接收解析JSON資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.