简单实现_实体类与Json字符串互相转换
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
文章目录
一、Jackson方式
1、实体类
public class Person {
private String name;
private int age;
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;
}
}
2、实体类转为Json
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
System.out.println("=============实体类转为Json=============");
Person person = new Person();
person.setAge(15);
person.setName("小明");
String result = mapper.writeValueAsString(person);
System.out.println(result);
System.out.println("=============Json转为实体类=============");
String str = "{\"name\":\"小明\",\"age\":15}";
Person person1 = mapper.readValue(str, Person.class);
System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge());
}
}
3、运行结果
4、Spring boot中使用
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
public class Test {
@Autowired
private ObjectMapper mapper;
public void test() throws JsonProcessingException {
System.out.println("=============实体类转为Json=============");
Person person = new Person();
person.setAge(15);
person.setName("小明");
String result = mapper.writeValueAsString(person);
System.out.println(result);
System.out.println("=============Json转为实体类=============");
String str = "{\"name\":\"小明\",\"age\":15}";
Person person1 = mapper.readValue(str, Person.class);
System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge());
}
}
二、FastJson方式
1)、案例
1、Pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
2、实体类
public class Person {
private String name;
private int age;
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;
}
3、实体类与Json转换
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) {
System.out.println("=============实体类转为Json=============");
Person person = new Person();
person.setAge(15);
person.setName("小明");
String result = JSON.toJSONString(person);
System.out.println(result);
System.out.println("=============Json转为实体类=============");
String str = "{\"name\":\"小明\",\"age\":15}";
Person person1 = JSON.parseObject(str, Person.class);
System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge());
}
}
4、运行结果
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e
5 个月前
8c391e04
8 个月前
更多推荐
已为社区贡献19条内容
所有评论(0)