1.什么是json
JSON是Javascript-Object-notation的简称,是一种轻量级的数据交换格式。
2.简单json的解析
@Test public void test1() { String jsonString = "{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"10371443@qq.com\"}"; JSONObject json = JSONObject.parseObject(jsonString); User user = new User(); user.setName(json.getString("name")); user.setPassword(json.getString("password")); user.setEmail(json.getString("email")); System.out.println(user.toString()); } @Data class User { private String name; private String password; private String email; }
将键值对的json字符串转换为json对象,然后获取json对象中的数据即可
3.企业返回对象的json解析
@Test public void test2() { // 假设这就是返回的json格式的字符串 String jsonString = "{\n" + " \"code\": \"10000\",\n" + " \"charge\": false,\n" + " \"remain\": 1305,\n" + " \"msg\": \"查询成功\",\n" + " \"result\": {\n" + " \"error_code\": 0,\n" + " \"reason\": \"成功\",\n" + " \"result\": {\n" + " \"realname\": \"乐天磊\",\n" + " \"idcard\": \"350721197702134399\",\n" + " \"isok\": true\n" + " }\n" + " }\n" + "}"; //使用fastjson解析json格式的字符串为json对象 JSONObject jsonObject = JSONObject.parseObject(jsonString); //获取通信标识code String code = jsonObject.getString("code"); //判断通信是否成功 // if (!StringUtils.equals("10000", code)) { // return StandardResult.faild("通信异常"); // } //获得业务处理结果,result中存储的也是json字符串 Boolean isok = jsonObject.getJSONObject("result").getJSONObject("result").getBoolean("isok"); System.out.println("isok = " + isok); String idcard = jsonObject.getJSONObject("result").getJSONObject("result").getString("idcard"); System.out.println("idcard = " + idcard); String realname = jsonObject.getJSONObject("result").getJSONObject("result").getString("realname"); System.out.println("realname = " + realname); // if (!isok) { // return Result.error("真实姓名和身份证号码不匹配"); // } }
将前端返回的企业返回对象转化为可用的数据
4.嵌套对象的json类型转化
@Test public void test3() { String str="{\n" + "\t\"name\": \"zhangsan\",\n" + "\t\"age\": \"18\",\n" + "\t\"score\": [{\n" + "\t\t\t\"year\": \"2016\",\n" + "\t\t\t\"yuwen\": \"60\",\n" + "\t\t\t\"shuxue\": \"60\",\n" + "\t\t\t\"yingyu\": \"60\"\n" + "\t\t},\n" + "\t\t{\n" + "\t\t\t\"year\": \"2017\",\n" + "\t\t\t\"yuwen\": \"80\",\n" + "\t\t\t\"shuxue\": \"80\",\n" + "\t\t\t\"yingyu\": \"80\"\n" + "\t\t},\n" + "\t\t{\n" + "\t\t\t\"year\": \"2018\",\n" + "\t\t\t\"yuwen\": \"100\",\n" + "\t\t\t\"shuxue\": \"100\",\n" + "\t\t\t\"yingyu\": \"100\"\n" + "\t\t}\n" + "\t]\n" + "}"; JsonRootBean jsonRootBean = JSONObject.parseObject(str, JsonRootBean.class); System.out.println("jsonRootBean = " + jsonRootBean); } @Data @ToString public static class JsonRootBean { private String name; private String age; private List<Score> score; @Data @ToString public static class Score { private String year; private String yuwen; private String shuxue; private String yingyu; } }
嵌套多个对象的json字符串转化为相应的对象
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/64432.html