json详解及应用

json作用

如果a要发送给b一些信息

通过xml:

<persons>
	<person>
  	<name>zhangsan</name>
    <age>18</age>
  </person>
  <person>
  	<name>lisi</name>
    <age>20</age>
  </person>
</persons>

这样解析起来很慢

如果通过json:

Person per = new Person() ;
per.setXxx() ; //设置一些属性

//json的形式:  key: value
"ZS":per
//发送给另一边,另一边直接get,效率高很多
per = json.getXxxx(" zs' ); 

应用

一些铺垫(需要的实体类)

//person:age,name,address;
//别的都是构造方法和set,get
//这里的address是另一个类,包含家庭地址和学校地址,在后面
public class Person {
	private int age;
	private String name;
  private Address address;
	public Person() {
	}
	public Person(int age, String name, Address address) {
		super();
		this.age = age;
		this.name = name;
		this.address = address;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
}
public class Address {
	String homeAddress;
	String schoolAddress;
  /* 后面就是构造方法和set,get*/
	public Address() {
	}
	public Address(String homeAddress, String schoolAddress) {
		super();
		this.homeAddress = homeAddress;
		this.schoolAddress = schoolAddress;
	}
	public String getHomeAddress() {
		return homeAddress;
	}
	public void setHomeAddress(String homeAddress) {
		this.homeAddress = homeAddress;
	}
	public String getSchoolAddress() {
		return schoolAddress;
	}
	public void setSchoolAddress(String schoolAddress) {
		this.schoolAddress = schoolAddress;
	}
}

----这里开始放大招----

json的应用其实就是各种转换

map => json

private static void map1() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("1", "zs");
		map.put("2","ls");
		map.put("3","ww");
		JSONObject json = new JSONObject(map);
		System.out.println(json);
		/*
		 * {"1":"zs","2":"ls","3":"ww"}
		 * */
}

对象=>json

private static void object2() {
		Person person = new Person();
		person.setName("zs");
		person.setAge(23);
		person.setAddress(new Address("西安","北京"));
		JSONObject json = new JSONObject(person);
		System.out.println(json);
		/*
{
"address":{"schoolAddress":"北京","homeAddress":"西安"},
"name":"zs",
"age":23
}
		 */
}

String => json

public static void string3() throws JSONException{
		// {"name":"zs","age":23}
		//上面的粘贴到“”内会自动转义
		String str = "{\"name\":\"zs\",\"age\":23}";
		JSONObject json = new JSONObject(str);
		System.out.println(json);
}

文件 => json

其实还需要中间再转换成string,即文件=> string => json

string=>json的方法和前面一样
文件=>string有两种方法:

方法一(超级麻烦):
public void file4() throws IOException, JSONException {
		//文件->String
		InputStream in = super.getClass().getClassLoader().getResourceAsStream("Test/person.json");
		byte[] bs = new byte[10];
		int len = -1;
		StringBuffer sb = new StringBuffer();
		while((len = in.read(bs))!=-1) {
			sb.append(new String(bs,0,len));
		}
		System.out.println(sb);
		//String->json
		JSONObject json = new JSONObject(sb.toString());
		System.out.println(json);
}
方法二(简单很多):
public static void file5() throws IOException, JSONException {
		//文件->String->json
		String string = FileUtils.readFileToString(new File("/Users/dylan/MyLibrary/EclipseWorkspace/JsonProject/src/Test/person.json"));
		JSONObject json = new JSONObject(string);
		System.out.println(json);
}

生成json文件

public static void json6() throws IOException, JSONException {
		Map<String,Person> map = new HashMap<>();
		Person p1 = new Person(23,"zs",new Address("xa","lz"));
		Person p2 = new Person(2,"ls",new Address("lz","cs"));
		Person p3 = new Person(3,"ww",new Address("cs","sh"));
		map.put("zs", p1);
		map.put("ls", p2);
		map.put("ww", p3);
		
		JSONObject json = new JSONObject(map);
		Writer writer = new FileWriter("/Users/dylan/desktop/jjj.json");
		json.write(writer);
		writer.close();
}

还有一个东西叫jsonArray

这里指的是org.json.JSONArray

在后续的学习中,我发现这玩!意!尔!不!怎!么!用!看看就好

public static void jsonArray7() throws IOException, JSONException {
		String str = "[{\"classname\":\"ljn\",\"classno\":1},{\"schoolname\":\"hnu\",\"zone\":\"cs\"}]";
		JSONArray array = new JSONArray(str);
		System.out.println(array);
}

这里是高级版的jsonArray

net.sf.json.JSONArray是新版的,现在大多数用这个

需要一些jar包(版本不重要啦):

commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
commons-beanutils-1.7.0.jar
commons-lang-2.4.jar
commons-collections-3.2.1.jar
Json-lib.jar

(我都放在GitHub 里了)

map=>jsonArray
public static void map2jsonArray8() throws IOException, JSONException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("1", "zs");
		map.put("2","ls");
		map.put("3","ww");
		net.sf.json.JSONArray jarray = new net.sf.json.JSONArray();
  //直接使用fromObject就可以转换
		jarray = jarray.fromObject(map);
		System.out.println(jarray);
}
jsonArray => map
public static void jsonArray2map9() {
		String string = "[{\"classname\":\"ljn\",\"classno\":1},{\"schoolname\":\"hnu\",\"zone\":\"cs\"}]";
		net.sf.json.JSONArray jarray = new net.sf.json.JSONArray();
  //先创建一个数组和map
		jarray = jarray.fromObject(string);
		Map<String,Object> map = new HashMap<>();
  //获取数组中的元素
		for(int i=0; i < jarray.size();i++){
      //这里获取到每一个对象
			Object o = jarray.get(i);
      //将object转化为json
		  net.sf.json.JSONObject json = (net.sf.json.JSONObject)o;
      //一个json中会有多个key,先获取全部的key
		  Set<String> keys = json.keySet();
      //再遍历所有的key
		  for(String key:keys){
        //从json中获取值
				Object value = json.get(key);
        //加到map中
		    map.put(key,value);
		  }
		}
		System.out.println(map);
}
发布了84 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Mercuriooo/article/details/104122611
今日推荐