json

来源:互联网 发布:单片机大学生毕业设计 编辑:程序博客网 时间:2024/04/30 03:29

JSON有两种表示结构,对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。

{    key1:value1,    key2:value2,    ...}

其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组

数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。

 后台对Json数据的处理

1  将数据以list 形式传给 前端 

list.add(data);

}JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
JSONArray json = JSONArray.fromObject(list, jsonConfig);

或者   JSONObject json  = new JSONObject();

jsom.put("list",list); //可添加数组 list  map 任意



2  过滤掉 指定的对象的属性

//json 数据 去除不必要的属性
jsonConfig.setJsonPropertyFilter( new PropertyFilter(){  


public boolean apply(Object source/* 属性的拥有者 */, String name /*属性名字*/, Object value/* 属性值 */ ){  
// return true to skip name  
return source instanceof user && name.equals("username");  
}  
});  
 
JSON json = JSONSerializer.toJSON( users, jsonConfig ) ; 
           System.out.println(json);

3  解析json 数据

Read {
    public static void main(String args[]){
        JsonParser parse =new JsonParser();  //创建json解析器
        try {
            JsonObject json=(JsonObject) parse.parse(new FileReader("weather.json"));  //创建jsonObject对象
            System.out.println("resultcode:"+json.get("resultcode").getAsInt());  //将json数据转为为int型的数据
            System.out.println("reason:"+json.get("reason").getAsString());     //将json数据转为为String型的数据
             
            JsonObject result=json.get("result").getAsJsonObject();
            JsonObject today=result.get("today").getAsJsonObject();
            System.out.println("temperature:"+today.get("temperature").getAsString());
            System.out.println("weather:"+today.get("weather").getAsString());
             
        catch (JsonIOException e) {
            e.printStackTrace();
        catch (JsonSyntaxException e) {
            e.printStackTrace();
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

复制代码
[    {        key1:value1,        key2:value2     },    {         key3:value3,         key4:value4       }

]

0 0