jackson相关操作

1、第一个例子

          ObjectMapper mapper = new ObjectMapper();
          String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
          try {
             Student student = mapper.readValue(jsonString, Student.class);
             mapper.enable(SerializationFeature.INDENT_OUTPUT);//格式化输出json字符串
             jsonString = mapper.writeValueAsString(student);
             System.out.println(jsonString);
          } catch (IOException e) {
             e.printStackTrace();
          }
输出:
{
  "name" : "Mahesh",
  "age" : 21
}

2、对象序列化到文件


    public static void main(String args[]){
          JacksonTester tester = new JacksonTester();
          try {
             Student student = new Student();
             student.setAge(10);
             student.setName("Mahesh");
             tester.writeJSON(student);
    
             Student student1 = tester.readJSON();
             System.out.println(student1);
    
          }  catch (IOException e) {
             e.printStackTrace();
          }
       }
 
       private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
          ObjectMapper mapper = new ObjectMapper();	
          mapper.writeValue(new File("student.json"), student);
       }
       private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
          ObjectMapper mapper = new ObjectMapper();
          Student student = mapper.readValue(new File("student.json"), Student.class);
          return student;
       }

3、json与简单类型数据绑定

序号json类型Java类型
1objectLinkedHashMap<String,Object>
2arrayArrayList
3stringString
4complete numberInteger, Long or BigInteger
5stfractional numberringDouble / BigDecimal
6truefalse
7nullnull

     public static void main(String args[]){
          JacksonTester tester = new JacksonTester();
             try {
                ObjectMapper mapper = new ObjectMapper();
                Map<String,Object> studentDataMap = new HashMap<String,Object>(); 
                int[] marks = {1,2,3};
    
                Student student = new Student();
                student.setAge(10);
                student.setName("Mahesh");
                // JAVA Object
                studentDataMap.put("student", student);
                // JAVA String
                studentDataMap.put("name", "Mahesh Kumar");   		
                // JAVA Boolean
                studentDataMap.put("verified", Boolean.FALSE);
                // Array
                studentDataMap.put("marks", marks);
    
                mapper.writeValue(new File("student.json"), studentDataMap);
                //result student.json文件里存储格式如下
    			//{ 
                //   "student":{"name":"Mahesh","age":10},
                //   "marks":[1,2,3],
                //   "verified":false,
                //   "name":"Mahesh Kumar"
                //}
                studentDataMap = mapper.readValue(new File("student.json"), Map.class);
          } } catch (IOException e) {
                e.printStackTrace();
          }
       }

4、Jackson与对象类型数据绑定

TypeReference对象的使用,强制类型转换

     public static void main(String args[]) {
            JacksonTester tester = new JacksonTester();
            try {
                ObjectMapper mapper = new ObjectMapper();
    
                Map<String, UserData> userDataMap = new HashMap();
                UserData studentData = new UserData();
                int[] marks = {1, 2, 3};
    
                Student student = new Student();
                student.setAge(10);
                student.setName("Mahesh");
                // JAVA Object
                studentData.setStudent(student);
                // JAVA String
                studentData.setName("Mahesh Kumar");
                // JAVA Boolean
                studentData.setVerified(Boolean.FALSE);
                // Array
                studentData.setMarks(marks);
    
                userDataMap.put("studentData1", studentData);
                mapper.writeValue(new File("student.json"), userDataMap);
                userDataMap = mapper.readValue(new File("student.json"), new TypeReference<Map<String, UserData>>() {
                });
            }  catch (IOException e) {
                e.printStackTrace();
            }
        }

5、json树模型

json字符串转换成jsonNode树,遍历树模型

 		ObjectMapper mapper = new ObjectMapper();
        String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
        JsonNode rootNode = mapper.readTree(jsonString);

        JsonNode nameNode = rootNode.path("name");
        System.out.println("Name: " + nameNode.textValue());

        JsonNode ageNode = rootNode.path("age");
        System.out.println("Age: " + ageNode.intValue());

        JsonNode verifiedNode = rootNode.path("verified");
        System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes" : "No"));

        JsonNode marksNode = rootNode.path("marks");
        Iterator<JsonNode> iterator = marksNode.elements();
        System.out.print("Marks: [ ");
        while (iterator.hasNext()) {
            JsonNode marks = iterator.next();
            System.out.print(marks.intValue() + " ");
        }
        System.out.println("]");

创建树,

   	    ObjectMapper mapper = new ObjectMapper();
        ObjectNode rootNode = mapper.createObjectNode();
        ArrayNode marksNode = mapper.createArrayNode();
        marksNode.add(100);
        marksNode.add(90);
        marksNode.add(85);
        rootNode.put("name", "Mahesh Kumar");
        rootNode.put("age", 21);
        rootNode.put("verified", false);
        rootNode.put("marks", marksNode);
        mapper.writeValue(new File("student.json"), rootNode);

jsonNode转换为student对象
如果rootNode含有student不包含的属性,会报错

         Student student = mapper.treeToValue(rootNode, Student.class);

6、流式API读取和写入JSON内容离散事件

JsonParser读取数据,而JsonGenerator写入数据。它是三者中最有效的方法,是最低开销和最快的读/写操作。它类似于XML的Stax解析器。
用JsonGenerator将数据写入student.json文件


     			JsonFactory jasonFactory = new JsonFactory();
                JsonGenerator jsonGenerator = jasonFactory.createGenerator(new File(
                        "student.json"), JsonEncoding.UTF8);
                jsonGenerator.writeStartObject();
                // "name" : "Mahesh Kumar"
                jsonGenerator.writeStringField("name", "Mahesh Kumar");
                // "age" : 21
                jsonGenerator.writeNumberField("age", 21);
                // "verified" : false
                jsonGenerator.writeBooleanField("verified", false);
                // "marks" : [100, 90, 85]
                jsonGenerator.writeFieldName("marks");
                // [
                jsonGenerator.writeStartArray();
                // 100, 90, 85
                jsonGenerator.writeNumber(100);
                jsonGenerator.writeNumber(90);
                jsonGenerator.writeNumber(85);
                // ]
                jsonGenerator.writeEndArray();
                jsonGenerator.writeEndObject();
                jsonGenerator.close();

用JsonParser读取数据

    		    JsonFactory jasonFactory = new JsonFactory();
                JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
                while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                    //get the current token
                    String fieldname = jsonParser.getCurrentName();
                    if ("name".equals(fieldname)) {
                        //move to next token
                        jsonParser.nextToken();
                        System.out.println(jsonParser.getText());
                    }
                    if ("age".equals(fieldname)) {
                        //move to next token
                        jsonParser.nextToken();
                        System.out.println(jsonParser.getNumberValue());
                    }
                    if ("verified".equals(fieldname)) {
                        //move to next token
                        jsonParser.nextToken();
                        System.out.println(jsonParser.getBooleanValue());
                    }
                    if ("marks".equals(fieldname)) {
                        //move to [
                        jsonParser.nextToken();
                        // loop till token equal to "]"
                        while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                            System.out.println(jsonParser.getNumberValue());
                        }
                    }
                }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值