1. 程式人生 > >json與CBOR的簡單示例

json與CBOR的簡單示例

用程式碼說話:

示例一:

import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;

public class NodeTest {
	   @Test
	   public void test() {
	      ObjectMapper mapper = new ObjectMapper(new CBORFactory());
	      try {

	         //====================組裝一個數組物件=======================
	         //--------------組裝陣列物件--------------
	         ArrayNode arrayNode = mapper.createArrayNode();
	         ObjectNode v1 = mapper.createObjectNode();
	         v1.put("temperature", 10);
	         ObjectNode v2 = mapper.createObjectNode();
	         v2.put("pressure", 0.01);
	         arrayNode.add(v1);
	         arrayNode.add(v2);
	         //--------------獲取二進位制流---------------
	         byte[] bytes = mapper.writeValueAsBytes(arrayNode);

	         //==================從 json 建立樹===========================
	         //create tree from JSON
	         JsonNode rootNode = mapper.readTree(bytes);
	         System.out.println(rootNode.toString());
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	   }
}

示例二:

import java.io.IOException;
import org.junit.Test;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;

public class ObjectMapperTest {
	   @Test
	   public void test() {
	      CBORFactory f = new CBORFactory();
	      ObjectMapper mapper = new ObjectMapper(f);

	      Student student = new Student();
	      student.setAge(10);
	      student.setName("daopinz");

	      //cbor to student
	      try {
	         byte[] bytes = mapper.writeValueAsBytes(student);
	         Student student2 = mapper.readValue(bytes, Student.class);
	         System.out.println(student2);
	      } catch (JsonParseException e) {
	         e.printStackTrace();
	      } catch (JsonMappingException e) {
	         e.printStackTrace();
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	   }


	   static class Student {
	      private String name;
	      private int age;

	      public Student() {
	      }

	      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 toString() {
	         return "Student [ name: " + name + ", age: " + age + " ]";
	      }
	   }
}