Java对象与JSON字符串互相转换
1.准备工作
在与前端页面交互时,经常需要传递json字符串数据,我们可以使用JSONObject来处理json字符串。
需要导入2个jar包:
fastjson-1.2.2.jar,fastjson-1.2.2-sources.jar
import com.alibaba.fastjson.JSONObject;import org.junit.Test;import java.util.*;
作为测试,先准备几个字符串数据:
private String s1 = " {\"AreaName\": \"北京\",\n" + " \"CityId\": 110100,\n" + " \"NoMarket\": false,\n" + " \"OldCityId\": 646,\n" + " \"Pinyin\": \"beijing\",\n" + " \"ProvinceId\": 110000}"; private String s2 = "[\n"+ " {\"name\":\"tom\",\"age\":18,\"gender\":\"男\"},\n"+ " {\"name\":\"lily\",\"age\":19,\"gender\":\"女\"},\n"+ " {\"name\":\"hanmeimei\",\"age\":17,\"gender\":\"女\"}]"; private String s3 = "{\"id\":1, \"from\":\"xiaoxin\", \n" + " \"result\":[\n" + " {\"age\":18,\"gender\":\"男\",\"name\":\"tom\"},\n" + " {\"age\":19,\"gender\":\"女\",\"name\":\"lily\"},\n" + " {\"age\":17,\"gender\":\"女\",\"name\":\"hanmeimei\"}]}"; private String s4 = "{\"age\":18,\"gender\":\"男\",\"name\":\"tom\"}"; private String s5 ="[1,2,3,4,5]";
2.字符串转对象
我们需要使用JSONObject.parse(),JSONObject.parseArray(),JSONObject.parseObject()三个方法来转换json数据,JSONObject.parse()获得后的数据需要强转为JSONObject才能进行下一步操作。
json字符串转为JSONObject对象后,操作数据与map类似,使用get()方法来获取数据,也可以使用getInteger(),getString()…等方法来获取数据。
若要转换为java对象,则需要创建一个有相应字段的类,下例中为User类
@Test public void test1(){ //json字符串转json对象,与map类似 //只写parse,需要强转,写parseObject,则直接得到JSONObject JSONObject jsonObject = (JSONObject) JSONObject.parse(s1); System.out.println(jsonObject);//{"AreaName":"北京","CityId":110100,"NoMarket":false,"OldCityId":646,"Pinyin":"beijing","ProvinceId":110000} //从json对象中获取值 String areaName = jsonObject.getString("AreaName"); System.out.println("----------------"); System.out.println(areaName); System.out.println(jsonObject.getInteger("OldCityId")); System.out.println(jsonObject.get("CityId")); System.out.println("----------------"); //遍历jsonObject jsonObject.forEach((key,value)-> System.out.println(key+"->"+value)); //将字符串转换为java对象 User user = JSON.parseObject(s4, User.class); System.out.println(user); }
User类:
public class User { private String name; private int age; private String gender; @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public User() { } public User(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; }}
转换json数组,需要使用 JSONObject.parseArray()方法,转换为JSONArray类,之后的操作方法与操作ArrayList类似。
@Test public void test2(){ //json对象数组字符串转json对象数组,相当于ArrayList JSONArray jsonS2 = JSONObject.parseArray(s2); System.out.println(jsonS2);//[{"age":18,"gender":"男","name":"tom"},{"age":19,"gender":"女","name":"lily"},{"age":17,"gender":"女","name":"hanmeimei"}] //获取索引为1的值,需要强转为JSONObject JSONObject o1 = (JSONObject)jsonS2.get(0); System.out.println(o1); //遍历// jsonS2.forEach(item-> System.out.println(item)); jsonS2.forEach(System.out::println); //转化为java ArrayList List<User> users = JSON.parseArray(s2, User.class); System.out.println(users); }
转化复杂的json数据,需要一步一步转换,获取相应的数据可以使用getJSONArray(),getJSONObject()方法
@Test public void test3(){ //复杂数据转json对象,与上面的一样 JSONObject objectS3 = JSONObject.parseObject(s3); //拿到result JSONArray JSONArray result = objectS3.getJSONArray("result"); //遍历result result.forEach(System.out::println); //获取指定索引的值 JSONObject o = result.getJSONObject(1); System.out.println(o.getString("name")); //lily //将json数组转换为List List<Integer> numArr = JSON.parseArray(s5, Integer.class); System.out.println(numArr); //将result转换为List对象 List<User> users = JSON.parseArray(objectS3.getJSONArray("result").toJSONString(), User.class); System.out.println(users);//[User{name='tom', age=18, gender='男'}, User{name='lily', age=19, gender='女'}, User{name='hanmeimei', age=17, gender='女'}] }
3.对象转字符串
先准备一个Map和一个List
private HashMap<String, String> map1 = new HashMap<String, String>();private List<String> list1 = new ArrayList<>();private List<User> list2 = new ArrayList<>();
使用JSONObject.toJSONString()方法来将对象转换为json字符串
@Test public void test1(){ map1.put("apple","新鲜的苹果"); //向集合中添加对象 map1.put("computer","配置优良的计算机"); map1.put("book","堆积成山的图书"); System.out.println(map1); //map对象转json字符串 String s = JSONObject.toJSONString(map1); System.out.println(s); //java对象转json字符串 String s1 = JSONObject.toJSONString(new User("tom", 18, "男")); System.out.println(s1); }
转换数组也是一样:
@Test public void test2(){ Collections.addAll(list1,"tom","18","男"); System.out.println(list1); //ArrayList转json字符串 String s = JSONObject.toJSONString(list1); System.out.println(s); //java对象的ArrayList转json字符串 Collections.addAll(list2,new User("tom",18,"男"),new User("lily",16,"女")); System.out.println(JSONObject.toJSONString(list2)); }