本文主要是介绍jason字符串解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class TestJson {
public static void main(String[] args) {
//要解析的对象
String json = “{ ‘desc’: ‘OK’, ” +
“‘status’: 1000, ” +
“‘data’: { ‘wendu’: ‘20’,” +
” ‘ganmao’: ‘相对于今天将会出现大幅度降温,易发生感冒,请注意适当增加衣服,加强自我防护避免感冒。’, ” +
“‘forecast’: [ { ‘fengxiang’: ‘北风’, ‘fengli’: ‘3-4级’, ‘high’: ‘高温 27℃’, ‘type’: ‘中雨’, ‘low’: ‘低温 19℃’, ‘date’: ‘6日星期五’ }, ” +
“{ ‘fengxiang’: ‘北风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 23℃’, ‘type’: ‘大雨’, ‘low’: ‘低温 17℃’, ‘date’: ‘7日星期六’ }, ” +
“{ ‘fengxiang’: ‘北风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 26℃’, ‘type’: ‘小雨’, ‘low’: ‘低温 17℃’, ‘date’: ‘8日星期天’ }, ” +
“{ ‘fengxiang’: ‘南风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 27℃’, ‘type’: ‘多云’, ‘low’: ‘低温 15℃’, ‘date’: ‘9日星期一’ },” +
” { ‘fengxiang’: ‘南风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 29℃’, ‘type’: ‘多云’, ‘low’: ‘低温 16℃’, ‘date’: ‘10日星期二’ } ], ” +
“‘yesterday’: { ‘fl’: ‘微风’, ‘fx’: ‘北风’, ‘high’: ‘高温 33℃’, ‘type’: ‘阴’, ‘low’: ‘低温 22℃’, ‘date’: ‘5日星期四’ },” +
” ‘aqi’: ‘58’,” +
” ‘city’: ‘成都’ } }”;
System.out.println("==================================================================================");//将解析的值存入对象之中Weather weather=new Weather();Data data=new Data();Forecast forecast=new Forecast();//将节点对象转换成Object对象JSONObject jsonObject1 = JSONObject.parseObject(json);//获取到data对象JSONObject data1 = jsonObject1.getJSONObject("data");//通过data对象获取到forecast数组JSONArray jsonArray = data1.getJSONArray("forecast");//遍历jsonArray数组,取出数组中的值for (int i = 0; i < jsonArray.size(); i++) {JSONObject object = (JSONObject) jsonArray.get(i);forecast.setFengxiang(object.getString("fengxiang"));forecast.setFengli(object.getString("fengli"));forecast.setHigh(object.getString("high"));forecast.setDate(object.getString("date"));}System.out.println("===================================================================================");//获取desc的值Object desc = jsonObject1.get("desc");System.out.println(desc);//获取ganmao的值Object ganmao = data1.get("ganmao");System.out.println(ganmao);//通过数组下标获取某个对象JSONObject jsonObject = (JSONObject) jsonArray.get(0);//通过key取到value值String type = jsonObject.getString("type");Object low = jsonObject.get("low");System.out.println(type);System.out.println(low);
}
}
做为一个菜鸟,第一次发。不喜勿喷,有错忘大家指正……
这篇关于jason字符串解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!