文章目录
1.Json对象转换为java 对象
2. Java对象转换JSON
1.Json对象转换为java 对象
导入jackson的相关jar包
创建Jackson核心对象 ObjectMapper
调用ObjectMapper的相关方法进行转换
@Test
public void test5() throws IOException {
//初始化Json对象
String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";
//创建ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//转换为java对象
Person person = mapper.readValue(json, Person.class);
System.out.println(person);
}
2. Java对象转换JSON
常见的解析器:Jsonlib,Gson,fastjson,jackson
1.导入jackson的相关jar包
2.创建Jackson核心对象 ObjectMapper
3.调用ObjectMapper的相关方法进行转换
public class JsonTest {
//java对象转换为JSON字符串
@Test
public void test1() throws IOException {
//1.创建Person对象
Person p = new Person();
p.setName("gh");
p.setAge(20);
p.setGender("女");
//2.创建jackson的核心对象
ObjectMapper mapper = new ObjectMapper();
//调用writeValueAsString方法装换
//String json = mapper.writeValueAsString(p);
//System.out.println(json);
//调用writeValue方法,将数据写到文件中
//mapper.writeValue(new File("f://a.txt"),p);
//调用writeValue方法,将数据写到字符输出流
mapper.writeValue(new FileWriter("f://b.txt"),p);
}
}
List集合转换为Json对象
@Test
public void test3() throws JsonProcessingException {
Person p = new Person();
p.setName("gh");
p.setAge(20);
p.setGender("女");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setName("gh");
p1.setAge(20);
p1.setGender("女");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("gh");
p2.setAge(20);
p2.setGender("女");
p2.setBirthday(new Date());
List<Person> ps = new ArrayList<Person>();
ps.add(p);
ps.add(p1);
ps.add(p2);
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(ps);
System.out.println(json);
}
Map集合转换为Json对象 文章来源:https://www.toymoban.com/news/detail-489249.html
@Test
public void test4() throws JsonProcessingException {
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","zhnagsan");
map.put("age",23);
map.put("gender","nv");
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
System.out.println(json);
}
使用注解将java对象装换为字符串
@JsonIgnore:排除属性
@JsonFormat:属性值格式化文章来源地址https://www.toymoban.com/news/detail-489249.html
public class Person {
private String name;
private String gender;
private int age;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
}
public class JsonTest {
@Test
public void test2() throws JsonProcessingException {
//1.创建Person对象
Person p = new Person();
p.setName("gh");
p.setAge(20);
p.setGender("女");
p.setBirthday(new Date());
//2.转换
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);
}
}
到了这里,关于java对象与Json字符串的相互转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!