JavaBean/字符串/map集合 与 JSON/JOSNArray 之间的相互转换

一、map、JavaBean、String、JSON文件 -> json数据

1、map -> json
Map<String, String> map = new HashMap<>();
map.put("s01","k01");
map.put("s02","k02");
map.put("s03","k03");
map.put("s04","k04");
//map->json
JSONObject jsonObject = new JSONObject(map);
System.out.println(jsonObject);

JSONObject jsonObject = new JSONObject(map);

打印结果:

{"s02":"k02","s01":"k01","s04":"k04","s03":"k03"}
2、JavaBean -> json
Person person = new Person();
person.setAge(17);
person.setName("张三");
Address add1 = new Address("西安","北京");
person.setAdress(add1);

//javaBean -> JSON
JSONObject jsonObject = new JSONObject(person);
System.out.println(jsonObject);

打印结果:

{"name":"张三",
 "adress":{"schoolAddress":"北京","homeAddress":"西安"}, 
 "age":17}

嵌套JavaBean

person类:
public class Person {
	private int age;
	private String name;
	private String phone;
	private Address adress;
	
	public Person() {
	}

	public Person(int age, String name, String phone, Address adress) {
		this.age = age;
		this.name = name;
		this.phone = phone;
		this.adress = adress;
	}

	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 String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Address getAdress() {
		return adress;
	}

	public void setAdress(Address adress) {
		this.adress = adress;
	}
}
Address类
package json;

public class Address {
	private String homeAddress;
	private String schoolAddress;
	
	public Address() {
	}
	
	public Address(String homeAdress, String schoolAdress) {
		this.homeAddress = homeAdress;
		this.schoolAddress = schoolAdress;
	}

	public String getHomeAddress() {
		return homeAddress;
	}
	public void setHomeAddress(String homeAdress) {
		this.homeAddress = homeAdress;
	}
	public String getSchoolAddress() {
		return schoolAddress;
	}
	public void setSchoolAddress(String schoolAdress) {
		this.schoolAddress = schoolAdress;
	}
	
}
3、String -> json
String str = "{\"name\":\"张三\",\"age\":23,\"phone\":\"12345678901\"}";
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject);

打印结果:

{"phone":"12345678901","name":"张三","age":23}
4、JOSN文件 -> json

备注:相当于读一个JSON文件,生成Json数据

思路:文件 -> 字符串 ->json

文件 -> 字符串 方式一 (读字节流)
InputStream in = super.getClass().getClassLoader().getResourceAsStream("json/test.json");
byte[] bs = new byte[10];
int length = -1;
StringBuffer sb = new StringBuffer();
while((length = in.read(bs))!=-1) {
    //			byte[] -> String
    String str = new String(bs,0,length);
    sb.append(str);
}
//		System.out.println(sb);
String str = sb.toString();
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject);

打印结果:

{"address":{"schoolAddress":"beijing","homeAddress":"xi'an"},"name":"zhangsan","age":23}

测试文件(test.json)

"name":"zhangsan"
"age": 23
"address":{"homeAddress":"xi'an","schoolAddress":"beijing"}
文件 -> 字符串 方式二 (导入commons-io.jar 包,直接调用函数)
String str = FileUtils.readFileToString(new File("H:\\java\\json\\src\\json\\test.json"));
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject);

打印结果:

{"address":{"schoolAddress":"beijing","homeAddress":"xi'an"},"name":"zhangsan","age":23}
总结

map、JavaBean对象、String -> JSON

JSONObject jsonObject = new JSONObject(map/javaBean/String);

二、生成JSON文件

备注:把Json数据写入到一个JSON文件中

思路:Json对象.write(…);

//准备json数据(用map来生成json数据)
Map<String, Person> map = new HashMap<>();
Person p1 = new Person(23,"张三","12345678901",new Address("北京","广东"));
Person p2 = new Person(24,"李四","12345678901",new Address("蓝山","恒基"));
Person p3 = new Person(25,"王五","12345678901",new Address("上海","深圳"));
map.put("张三",p1);
map.put("李四",p2);
map.put("王五",p3);
// map -> json
JSONObject jsonObject = new JSONObject(map);
//生成JSON文件
Writer writer = new FileWriter("H:\\\\java\\\\json\\\\src\\\\json\\\\result.json");
jsonObject.write(writer);
writer.close();

核心代码:jsonObject.write(writer);

运行结果:

{"李四":{"phone":"12345678901","name":"李四","adress":{"schoolAddress":"恒基","homeAddress":"蓝山"},"age":24},"张三":{"phone":"12345678901","name":"张三","adress":{"schoolAddress":"广东","homeAddress":"北京"},"age":23},"王五":{"phone":"12345678901","name":"王五","adress":{"schoolAddress":"深圳","homeAddress":"上海"},"age":25}}

三、JsonArray

1、字符串 -> JSONArray

备注:了解、生成json数组,如何把字符串形式的json数组生成真正的json数据的数组

String JsonArrayStr = "[{\"name\":\"张三\",\"age\":23,\"phone\":\"12345678901\"},"
				             + "{\"classNo\":1518,\"studentNo\":\"1234567\"},"
				             + "{\"homeAddress\":\"厦门\",\"schoolAddress\":\"湖南长沙\"}]";
JSONArray jsonArray = new JSONArray(JsonArrayStr);
System.out.println(jsonArray);

打印结果:

[{"phone":"12345678901","name":"张三","age":23},{"classNo":1518,"studentNo":"1234567"},{"schoolAddress":"湖南长沙","homeAddress":"厦门"}]
2、map -> JSONArray

重点:有关json类型转换更强大的一个库是:json-lib.jar

备注:json-lib.jar这个库依赖了很多其他的库

注意:有冲突!JSONArray既存在json.jar包中,又存在json-lib.jar包中。所以我们定义的时候要指定是哪个jar包中的JSONArray.

map转换JOSNArray(传统的jar包json已经满足不了了,所以在此例中我们引入json-lib.jar包)

Map<String,String> map = new HashMap<>();
map.put("张三","河南郑州");
map.put("李四","河南安阳");
map.put("王五","河南南阳");

net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
//map -> jsonArray
jsonArray = jsonArray.fromObject(map);
System.out.println(jsonArray);

核心代码:

net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();

jsonArray = jsonArray.fromObject(map);

打印结果:

[{"phone":"12345678901","name":"张三","age":23},
{"classNo":1518,"studentNo":"1234567"},
{"schoolAddress":"湖南长沙","homeAddress":"厦门"}]
3、JSONArray -> map

思路:获取每一个json数据,然后取出json数据的key 和 value,然后再赋给map

//准备JSONArray数据
String JsonArrayStr = "[{\"name\":\"张三\",\"age\":23,\"phone\":\"12345678901\"},"
    + "{\"classNo\":1518,\"studentNo\":\"1234567\"},"
    + "{\"homeAddress\":\"厦门\",\"schoolAddress\":\"湖南长沙\"}]";
net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
jsonArray = jsonArray.fromObject(JsonArrayStr);
Map<String, Object> map = new HashMap<>();
//获取每一个json
for(int i=0;i<jsonArray.size();i++) {
    Object object = jsonArray.get(i);
    net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject) object;
    //获取json数据的key/value
    //注意:每个json数据可能有多个key/value,
    //例如{\"name\":\"张三\",\"age\":23,\"phone\":\"12345678901\"}
    Set<String> keys = jsonObject.keySet();
    for(String key:keys) { //遍历json的每个key
        Object value = jsonObject.get(key);  //根据key找到value
        map.put(key,value);
    }
}
System.out.println(map);

打印结果:

{phone=12345678901, name=张三, classNo=1518, studentNo=1234567, schoolAddress=湖南长沙, age=23, homeAddress=厦门}

四、有关json-lib

json-lib 新包是通用的,可以替换json.jar中之前写的方法。

json.jar中:

JSONObject jsonObject = new JSONObject(str);

json-lib.jar中:

//		JSONObject jsonObject = new JSONObject(str);
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		jsonObject = jsonObject.fromObject(str);

打印结果:

{"name":"张三","age":23,"phone":"12345678901"}

其他的转换同理。

核心代码:

net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
jsonObject = jsonObject.fromObject(String/JavaBean/map);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值