第十一周作业关于json

json文件的实例:

json文件:
{
"name":"王小二",
"age":25.2,
"birthday":"1990-01-01",
"school":"蓝翔",
"major(技能)":["理发","挖掘机"],
"has_girlfriend":false,
"car":null,
"house":null,
"comment":"这是一个注释"
}

json文件的解析:
---------------------

package Json.json;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
*
* 解析json数据。
* */

public class ReadJSONSample {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = JSONObject.fromObject(content);
if (jsonObject.containsKey("name")) {
System.out.println("姓名是:"+jsonObject.getString("name"));
}
if(jsonObject.containsKey("nickname")) {
System.out.println("姓名是:"+jsonObject.getString("nickname"));
}
//System.out.println("姓名是:"+jsonObject.getString("name"));
System.out.println("年龄:"+jsonObject.getDouble("age"));
System.out.println("有没有女朋友:"+jsonObject.getBoolean("has_girlfriend"));
JSONArray majorArray = jsonObject.getJSONArray("major");
Iterator<?> iterator = majorArray.iterator();
int i = 0;
if (iterator.hasNext()) {
System.out.println((String)majorArray.get(i));
i++;
}
}

转载原文:https://blog.csdn.net/milustarting/article/details/79676419

posted @ 2018-11-26 13:36  似水流年掩盖不了难过  阅读(157)  评论(0编辑  收藏  举报