四时宝库

程序员的知识宝库

java实体对象与json字符串互转(java json对象和json字符串互转的方法)

(1)将java实体对象与json字符串互转

public class Helloworld {
	    private void jsonParseObject() throws Exception {
        String studentJsons = "{\"name\":\"Lily\", \"age\":\"9\"}";
        StudentPo studentPo = JSON.parseObject(studentJsons, StudentPo.class);
        System.out.println("解析json字符串成java实体对象其属性age值:" + studentPo.getAge());

        String studentConvertJs = JSON.toJSONString(studentPo);
        System.out.println("把java实体对象转换成json字符串:" + studentConvertJs);
    }
	public static void main(String[] args) throws Exception {
		// 测试代码
		new Helloworld().jsonParseObject();
	}
}

(2)java集合List转成json字符串 或 把json字符串集合转化成java集合对象

public class Helloworld {
	private void jsonParseObject() throws Exception {
        StudentPo studentPoV1 = new StudentPo();
        StudentPo studentPoV2 = new StudentPo();
        studentPoV1.setAge("1");
        studentPoV1.setName("n1");
        studentPoV2.setName("n2");
        studentPoV2.setAge("2");
        List<StudentPo> spoList = new ArrayList<StudentPo>();
        spoList.add(studentPoV1);
        spoList.add(studentPoV2);
        String listJson = JSONArray.toJSONString(spoList);
        System.out.println("java集合List转成json字符串:"+ listJson);

        List<StudentPo> jsonConvertList = JSONArray.parseArray(listJson, StudentPo.class);
        System.out.println("把json字符串集合转化成java集合对象:" + jsonConvertList.get(0).getName());
    }
	public static void main(String[] args) throws Exception {
		// 测试代码
		new Helloworld().jsonParseObject();
	}
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接