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類型
1 object LinkedHashMap<String,Object>
2 array ArrayList
3 string String
4 complete number Integer, Long or BigInteger
5 stfractional numberring Double / BigDecimal
6 true false
7 null null

     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());
                        }
                    }
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章