JSON的两种解析方式

1.JSON的定义

JSON: JavaScript Object NotationJavaScript对象表示法)。
是存储和交换文本信息的语法,类似xml。 但是比xml更小、更快、更易解析。
JSON说明:http://www.json.org/json-zh.html

2.JSON语法
数据在 名称/值对中(键值对)
数据由逗号分隔
花括号保存对象
方括号保存数组(集合)
{
    "setboxes": [
        {
            "province": "广东",
            "model": "msd11111",
            "setboxId": 0,
            "reserved": null,
            "vendor": "满洲",
            "protocolId": 0,
            "city": "深圳"
        },
        {
            "province": "广东",
            "model": "TT10010",
            "setboxId": 1,
            "reserved": null,
            "vendor": "同洲",
            "protocolId": 1,
            "city": "深圳"
        }
    ],
    "reserved": null,
    "version": 0.01,
    "selectedId": -1
}

3.JSON的一种解析(JSONObject&JSONArray)
public class IOUtil {
	
	public static String readStreamAsString(InputStream inputStream) throws IOException{
		
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream,"UTF-8"));
		String tempData = "";
		StringBuilder sbBuilder = new StringBuilder();
		while((tempData=bufferedReader.readLine())!=null){
			sbBuilder.append(tempData);
		}
		inputStream.close();
		
		return sbBuilder.toString();
	}

}
//String json 不是文件名,而是由提供文件得到的String。
String json = IOUtil.readStreamAsString(new  FileInputStream("StbModelMap.json"));

JSONObject jo = new JSONObject(String json); 
//getXXX中的参数直接是JSON文件中对应的名称
System.out.println("version:"+jo.getDouble("version"));
System.out.println("selectedId:"+jo.getInt("selectedId"));
JSONArray ja = jo.getJSONArray("setboxes");
for(int i=0;i<ja.elngth();i++){
JSONObject jsonObject = (JSONObject )ja.get(i);
 System.out.println("setboxId:"+ jsonObject .getInt("selectedId"));
models.add(jsonObject .getString("model"));
provinces.add(jsonObject .getString("province"));
}
修改在json信息后再写入json文件:
public static void main(String[] args) throws UnsupportedEncodingException,
            FileNotFoundException, IOException {
        String s = IOUtil.readStreamAsString(new FileInputStream(
                "StbModelMap.json"));
        JSONObject jsonObject = new JSONObject(s);
        jsonObject.put("selectedId", 5);
        FileOutputStream outputStream = new FileOutputStream("StbModelMap.json");
        outputStream.write(jsonObject.toString().getBytes());
        outputStream.flush();
        outputStream.close();
    }
注:若models.add(jsonObject .getString("model"));中的"model"字符串不正确,例如写成了"a",则province和model都不能正确解析。

4.JSON的另一种解析(Fastjson)

需要导入jar包--------fastjson-1.1.38.jar
需要自己根据json文件中的信息,创建class,一级一级的创建class,例如上面的信息,要创建两个class,如下:
public class Setboxes {
    private int setboxId = 0;
    private String province = null;
    private String model = null;
    private String vendor = null;
    private int protocolId = 0;
    private String city = null;
    private String reserved = null;
}
public class Info {
    private String reserved = null;
    private double version = 0.00;
    private int selectedId = 0;
    private Setboxes setboxes = null;
}
没加getXXX和setXXX。

然后再根据class的信息,来反射,得到class的对象。

public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO Auto-generated method stub
        //从json文件得到json的String
        String jsonString = IOUtil.readStraemAsString(new FileInputStream("StbModelMap.json"));
        //解析json
        Info jsonInfo = JSON.parseObject(jsonString,Info.class);
        //设置得到的json信息selectedId的值
        jsonInfo.setSelectedId(jsonInfo.getSetboxes().getSetboxId());
        FileOutputStream fileOutputStream = new FileOutputStream("StbModelMap.json");
        //把更改后的json信息再次写入json文件
        fileOutputStream.write(JSON.toJSONString(jsonInfo).getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
    }
注:parseObject()相当于:

Info info  = new Info;
info.setXxx("xxx");
info.setXxx("xxx");
return info;
这就是反射做的事情。


5.Fastjson

Alibaba开源项目,是一个Java语言编写的高性能功能完善的JSON库。

主要方法:

public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。


链接一篇好的Fastjson介绍: 点击打开链接







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值