zoukankan      html  css  js  c++  java
  • JAVA中使用JSON进行数据传递

    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":true
    9 }


    转自:https://www.cnblogs.com/UniqueColor/p/5724795.html
  • 相关阅读:
    JavaScript的兼容小坑和调试小技巧
    前端jQuery实现瀑布流
    angular常用属性大全
    Eclipse易卡死
    工作反思
    半年回忆
    努力做到
    产品经理如何应对技术的「做不了」这样的问题(转)
    优秀的产品经理我还有多远
    简历技巧
  • 原文地址:https://www.cnblogs.com/heiming/p/8399117.html
Copyright © 2011-2022 走看看