您的位置:首页 > 移动开发 > Objective-C

java中Array/List/Map/Object与Json互相转换详解

2016-05-19 20:14 561 查看
JSON(JavaScript Object Notation): 是一种轻量级的数据交换格式

一、JSON建构有两种结构:对象和数组

1、对象:对象在js中表示为“{}”扩起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。
2、数组:数组在js中是中括号“[]”扩起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。
经过对象、数组2种结构就可以组合成复杂的数据结构了。
二、具体形式
1、对象
(1)一个对象以“{”(左括号)开始,“}”(右括号)结束。

(2)每个“名称”后跟一个“:”(冒号)
(3)“‘名称/值’ 对”之间使用“,”(逗号)分隔
例子:表示人的一个对象:
{
"姓名" : "大憨",
"年龄" : 24
}
2、数组是值(value)的有序集合。
(1)一个数组以“[”(左中括号)开始,“]”(右中括号)结束。
(2)值之间使用“,”(逗号)分隔。
例子:一组学生
{
"学生" :
[
{"姓名" : "小明" , "年龄" : 23},
{"姓名" : "大憨" , "年龄" : 24}
]
}
说明:此Json对象包括了一个学生数组,而学生数组中的值又是两个Json对象。
说了这些基本了解json的数据结构了...

补充:在线Json校验格式化工具:http://www.bejson.com/go.php?u=http://www.bejson.com/index.php

三、老样子上次demo

这时我的工程结构图:上面引用到的外部库大家网上搜索下载~



configdata.json:

[javascript] view
plain copy

[  

    true,  

    false,  

    true  

]  

Address类:

[java] view
plain copy

/**    

 * @Title: 创建Address实体类的POJO 

 * @Description: TODO(用一句话描述该文件做什么) 

 * @author Potter    

 * @date 2013-2-18 上午10:16:03 

 * @version V1.0    

 */  

  

public class Address {  

    private String street;//街道  

    private String city;//城市  

    private int zip;//邮编  

    private String tel;//第一个电话号码  

    private String telTwo;//第二个电话号码  

  

    public Address() {  

    }  

  

    public Address(String street, String city, int zip, String tel, String telTwo){  

        this.street = street;  

        this.city = city;  

        this.zip = zip;  

        this.tel = tel;  

        this.telTwo = telTwo;  

    }  

      

    public String getStreet() {  

        return street;  

    }  

  

    public void setStreet(String street) {  

        this.street = street;  

    }  

  

    public String getCity() {  

        return city;  

    }  

  

    public void setCity(String city) {  

        this.city = city;  

    }  

  

    public int getZip() {  

        return zip;  

    }  

  

    public void setZip(int zip) {  

        this.zip = zip;  

    }  

  

    public String getTel() {  

        return tel;  

    }  

  

    public void setTel(String tel) {  

        this.tel = tel;  

    }  

  

    public String getTelTwo() {  

        return telTwo;  

    }  

  

    public void setTelTwo(String telTwo) {  

        this.telTwo = telTwo;  

    }  

}  

 

JsonTest类:

[java] view
plain copy

import java.io.File;  

import java.io.FileNotFoundException;  

import java.io.FileReader;  

import java.io.IOException;  

import java.util.ArrayList;  

import java.util.LinkedHashMap;  

import java.util.List;  

import java.util.Map;  

  

import net.sf.ezmorph.bean.MorphDynaBean;  

import net.sf.json.JSONArray;  

import net.sf.json.JSONFunction;  

import net.sf.json.JSONObject;  

  

public class JsonTest {  

  

    public static void main(String args[]) {  

        //javaArray和json互相转换  

        javaArrayAndJsonInterChange();  

        System.out.println("-------------------------------------");  

        //javaList和json互相转换  

        javaListAndJsonInterChange();  

        System.out.println("-------------------------------------");  

        //javaMpa和Json互转  

        javaMapAndJsonInterChange();  

        System.out.println("-------------------------------------");  

        //javaObject和jsonObject互转  

        javaObjectAndJsonInterChange();  

    }  

  

    /** 

     * javaArray和json互相转换 

     */  

    public static void javaArrayAndJsonInterChange() {  

        // java 转数组  

        boolean[] boolArray = new boolean[] { true, false, true };  

        JSONArray jsonArray = JSONArray.fromObject(boolArray);  

        String s = jsonArray.toString();  

        System.out.println(s);  

  

        // 通过json获取数组中的数据  

        String result = readJson("configdata");  

  

        JSONArray jsonR = JSONArray.fromObject(result);  

        int size = jsonR.size();  

        for (int i = 0; i < size; i++) {  

            System.out.println(jsonR.get(i));  

        }  

    }  

  

    /** 

     * javaList和json互相转换 

     */  

    public static void javaListAndJsonInterChange() {  

        List list = new ArrayList();  

        list.add(new Integer(1));  

        list.add(new Boolean(true));  

        list.add(new Character('j'));  

        list.add(new char[] { 'j', 's', 'o', 'n' });  

        list.add(null);  

        list.add("json");  

        list.add(new String[] { "json", "-", "lib" });  

  

        // list转JSONArray  

        JSONArray jsArr = JSONArray.fromObject(list);  

        System.out.println(jsArr.toString(4));  

  

        // 从JSON串到JSONArray  

        jsArr = JSONArray.fromObject(jsArr.toString());  

        // --从JSONArray里读取  

        // print: json  

        System.out.println(((JSONArray) jsArr.get(6)).get(0));  

    }  

  

    /** 

     * javaMpa和Json互转 

     */  

    public static void javaMapAndJsonInterChange() {  

        Map map = new LinkedHashMap();  

        map.put("integer", new Integer(1));  

        map.put("boolean", new Boolean(true));  

        map.put("char", new Character('j'));  

        map.put("charArr", new char[] { 'j', 's', 'o', 'n' });  

        // 注:不能以null为键名,否则运行报net.sf.json.JSONException:  

        // java.lang.NullPointerException:  

        // JSON keys must not be null nor the 'null' string.  

        map.put("nullAttr", null);  

  

        map.put("str", "json");  

        map.put("strArr", new String[] { "json", "-", "lib" });  

        map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)"));  

        map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098"));  

        // map转JSONArray  

        JSONObject jsObj = JSONObject.fromObject(map);  

        System.out.println(jsObj.toString(4));  

          

        // 从JSON串到JSONObject  

        jsObj = JSONObject.fromObject(jsObj.toString());  

  

        //第一种方式:从JSONObject里读取  

        // print: json  

        System.out.println(jsObj.get("str"));  

        // print: address.city = Seattle, WA    

        System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));    

  

          

        //第二种方式:从动态Bean里读取数据,由于不能转换成具体的Bean,感觉没有多大用处  

        MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);  

        // print: json  

        System.out.println(mdBean.get("str"));  

        //print: address.city = Seattle, WA    

        System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));    

  

    }  

      

    /** 

     * javaObject和jsonObject互转 

     */  

    public static void  javaObjectAndJsonInterChange(){  

        Address address=new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098");  

        //object转JSONObject  

        JSONObject jsObj = JSONObject.fromObject(address);  

        System.out.println(jsObj.toString(4));  

          

        //JsonObject转java Object  

          

        Address addressResult=(Address) JSONObject.toBean(jsObj, Address.class);  

        System.out.println("address.city = "+ addressResult.getCity());  

        System.out.println("address.street="+addressResult.getStreet());  

        System.out.println("address.tel = "+ addressResult.getTel());  

        System.out.println("address.telTwo="+addressResult.getTelTwo());  

        System.out.println("address.zip="+addressResult.getZip());  

    }  

  

    /** 

     * 读取json文件 

     * @param fileName 文件名,不需要后缀 

     * @return 

     */  

    public static String readJson(String fileName) {  

        String result = null;  

        try {  

            File myFile = new File("./config/" + fileName + ".json");  

            FileReader fr = new FileReader(myFile);  

            char[] contents = new char[(int) myFile.length()];  

            fr.read(contents, 0, (int) myFile.length());  

            result = new String(contents);  

            fr.close();  

        } catch (FileNotFoundException e) {  

            e.printStackTrace();  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

        return result;  

    }  

}  

哈哈~  没想到其实挺简单的!!!

 

参看文章:

http://jiangzhengjun.iteye.com/blog/463769

http://blog.csdn.net/chenzhehui/article/details/4067482

http://baike.baidu.com/view/136475.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: