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 + " ]";
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南