JSON - 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 + " ]";
}
}
}