JAVA中使用JSON進行資料傳遞

來源:互聯網
上載者:User

標籤:gic   之間   用戶端   前端   ddp   tomcat   關係   服務   port   

1.是不是只有xml傳遞資料的技術才是webservice?
可以這麼理解。webservice是基於SOAP協議,SOAP協議是基於XML的文本協議。所以webservice可以簡單理解為是基於XML的傳輸技術,好比HTML是基於文本的傳輸協議。
2.servlet是服務端的java程式的統稱?
不是。 servlet本質上是一個普通的Java程式,但他是支援某個標準的Java程式,這個標準就是Servlet規範。除了Java中的servlet程式要滿足Servlet規範、Tomcat、JBoss、WebLogic等這些Java伺服器程式也得遵循Servlet規範。

3.webservice可不可以通過json傳遞資料?
不可以。webservice是基於XML的。
4.json和xml是不是並列關係?
並列關係。json和xml都是描述資料的,是實現同一目的的不同手段,你寄快遞可以選EMS也可選中通。
5.http+json是什麼概念?
這個是個應用性的東西。大家喜歡http+json的原因,主要在於json的javascript的相容性比較好,寫程式簡單方便。
舉個例子:發給你的快遞都是空運的方式(傳輸協議是HTTP),但一種快遞是以箱子(html)打包,一種快遞是以袋子(json)打包,兩種都可以給你發快遞,但有的情況箱子方便,有的情況袋子方便。
6.我現在通過tomcat+axis2發布了一個web service,計算兩個整數的和,可以通過瀏覽器訪問。這是一個webservice嗎?
是的。
7.我在axis2下的tomcat/webappps/axis2/web-info/下建立了一個poco檔案夾,把class類型的java程式放了進去,一般伺服器是這樣部署嗎?
不是。一般是把Web工程,匯出為war包,再把war包複製到tomcat/webappps/目錄下。
webservice工程本質上也是個普通的Java Web工程,原理一樣。 網上或教程中多講熱發布Webservice,我覺得在實際中沒什麼用,一般重新發布webservice都涉及重新部署或重啟伺服器。

 

在介面的訪問和資料的傳輸方面使用的比較多的是使用JSON對象來操作格式化資料:在伺服器端採用JSON字串來傳遞資料並在WEB前端或者Android用戶端使用JSON來解析接收到的資料。

     首先,在JAVA中使用JSON需要引入 org.json 包(點擊 這裡 可以下載相應的JAR包!), 並在程式中引入相應的JSON類:

    

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

   

    其次,在伺服器端的Servlet類中,可以使用如下方法收集資料並產生相應的JSON字串

 

1 //聲明一個Hash對象並添加資料2 Map params =  new HashMap();3 4 params.put("username", username);5 params.put("user_json", user);6 7 //聲明JSONArray對象並輸入JSON字串8 JSONArray array = JSONArray.fromObject(params);9 put.println(array.toString());

 

   在WEB前端可以通過javascript直接對JSON字串進行解析,在Android用戶端的話,需要使用JSON類來解析字串:

 

 1 //@description: 根據接收到的JSON字串來解析字串中所包含的資料和資料對象 2  3 //接收到的JSON字串 4 String result = "[{\"username\": \"your name\", \"user_json\": {\"username\": \"your name\", \"nickname\": \"your nickname\"}}]"; 5  6 //根據字串產生JSON對象 7 JSONArray resultArray = new JSONArray(result); 8 JSONObject resultObj = resultArray.optJSONObject(0); 9 10 //擷取資料項目11 String username = resultObj.getString("username");12 13 //擷取資料對象14 JSONObject user = resultObj.getJSONObject("user_json");15 String nickname = user.getString("nickname");

 

 其實,主要就是涉及到以下集中資料類型之間的轉換:

1. String 轉換為JSON對象

 

 1 import org.json.JSONArray; 2 import org.json.JSONException; 3 import org.json.JSONObject; 4  5 //別忘了添加上JSON包哦! 6 public class StringToJSON { 7     public static void main(String[] args) throws JSONException{ 8          9         System.out.println("abc");10         //定義JSON字串11         String jsonStr = "{\"id\": 2," + 12                 " \"title\": \"json title\", " + 13                 "\"config\": {" +14                     "\"width\": 34," +15                     "\"height\": 35," +16                 "}, \"data\": [" +17                     "\"JAVA\", \"JavaScript\", \"PHP\"" +18                 "]}";19         20         //轉換成為JSONObject對象21         JSONObject jsonObj = new JSONObject(jsonStr);22         23         //從JSONObject對象中擷取資料24         JavaBean bean = new JavaBean();25         26         //根據屬性名稱擷取int型資料;27         bean.setId(jsonObj.getInt("id"));     28         29         //根據屬性名稱擷取String資料;30         bean.setTitle(jsonObj.getString("title")); 31         32         //根據屬性名稱擷取JSONObject類33         JSONObject config = jsonObj.getJSONObject("config");34         bean.setWidth(config.getInt("width"));35         bean.setHeight(config.getInt("height"));36         37         //根據屬性名稱擷取JSONArray數組38         JSONArray data = jsonObj.getJSONArray("data");39         for(int index = 0, length = data.length(); index < length; index++) {40             //這裡在org.json.JSONArray對象中居然沒有找到toArray方法,求各位網友給出解決辦法啊!41 //            bean.setLanguages(String[]);42         }        43     }44 }45 46 class JavaBean{47     private int id ;48     private String title;49     private int width;50     private int height;51     private String[] languages;52 53         //這裡省略了設定器和訪問器54 }

 

2. JSON對象轉換為String字串

 

 1 public static void main(String[] args) throws JSONException { 2          3         //建立JSONObject對象 4         JSONObject json = new JSONObject(); 5          6         //向json中添加資料 7         json.put("username", "wanglihong"); 8         json.put("height", 12.5); 9         json.put("age", 24);10         11         //建立JSONArray數組,並將json添加到數組12         JSONArray array = new JSONArray();13         array.put(json);14         15         //轉換為字串16         String jsonStr = array.toString();17         18         System.out.println(jsonStr);19     }

 

最終輸出結果為: [{"username":"wanglihong","height":12.5,"age":24}]  

3. 集合轉換為JSONArray對象

 

public static void main(String[] args)throws JSONException{        //初始化ArrayList集合并添加資料        List<String> list = new ArrayList<String>();        list.add("username");        list.add("age");        list.add("sex");                //初始化HashMap集合并添加數組        Map map = new HashMap();        map.put("bookname", "CSS3實戰");        map.put("price", 69.0);                //初始化JSONArray對象,並添加資料        JSONArray array = new JSONArray();        array.put(list);        array.put(map);                //產生的JSON字串為:[["username","age","sex"],{"price":69,"bookname":"CSS3實戰"}]    }

 

 

個人寫的讀寫json資料簡單樣本:

讀:

 1 import java.io.FileNotFoundException; 2 import java.io.FileReader; 3  4 import com.google.gson.JsonArray; 5 import com.google.gson.JsonIOException; 6 import com.google.gson.JsonObject; 7 import com.google.gson.JsonParser; 8 import com.google.gson.JsonSyntaxException; 9 10 public class Json_read {11 12     public static void main(String[] args) {13         14         try {15             JsonParser parser = new JsonParser();16             JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));17             System.out.println("cat="+object.get("cat").getAsString());18             System.out.println("pop="+object.get("pop").getAsBoolean());19             20             JsonArray array = object.get("languages").getAsJsonArray();21             for(int i=0;i<array.size();i++){22                 System.out.println("--------");23                 JsonObject subObject = array.get(i).getAsJsonObject();24                 System.out.println("id="+subObject.get("id").getAsInt());25                 System.out.println("name="+subObject.get("name").getAsString());26                 System.out.println("ide="+subObject.get("ide").getAsString());27                 28             }29             30         } catch (JsonIOException e) {31             e.printStackTrace();32         } catch (JsonSyntaxException e) {33             e.printStackTrace();34         } catch (FileNotFoundException e) {35             e.printStackTrace();36         }37     }38 39 }40   

寫:

import com.google.gson.JsonArray;import com.google.gson.JsonObject;public class Json_Write {    public static void main(String[] args) {        JsonObject object = new JsonObject();//整體jsonobject容器        object.addProperty("cat", "it");                JsonArray array = new JsonArray();                JsonObject lan1 = new JsonObject();        lan1.addProperty("id", 1);        lan1.addProperty("name", "java");        lan1.addProperty("ide", "eclipse");        array.add(lan1);                JsonObject lan2 = new JsonObject();        lan2.addProperty("id", 2);        lan2.addProperty("name", "switf");        lan2.addProperty("ide", "XCode");        array.add(lan2);                JsonObject lan3 = new JsonObject();        lan3.addProperty("id", 3);        lan3.addProperty("name", "c#");        lan3.addProperty("ide", "visual studio");        array.add(lan3);                object.add("languages", array);                object.addProperty("pop", true);                System.out.println(object.toString());            }}

test.json

1 {2    "cat":"it",3    "languages":[4       {"id":1,"ide":"Eclipse","name":"Java"},5       {"id":2,"ide":"XCode","name":"Swift"},6       {"id":3,"ide":"Visual studio","name":"c#"}7    ],8    "pop":true9 }


轉自:https://www.cnblogs.com/UniqueColor/p/5724795.html

JAVA中使用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.