springboot中json转换默认使用的是jackson包,通过spring-boot-starter-web依赖的
1 在属性上添加注解@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
可以修改对象转成json后的时间格式
2 在属性上添加注解 @JsonInclude(JsonInclude.Include.NON_NULL)
如果该属性为null,则不序列化
Include.Include.ALWAYS 默认
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化
Include.NON_NULL 属性为NULL 不序列化
3 在属性上添加注解 @JsonProperty("userName")
这里的别名'userName' ,可以有两个作用
一,当对象转为json时,该属性的key就是别名。
二,当json转为对象时,像这种格式{"id":100,"phone":"15211115013","name.wx":"zs"} , "name,wx" 就要为属性设置别名,否则转换会出错
4 在属性上添加注解@JsonIgnore 会忽略该属性,不会向前台返回该属性
import java.io.IOException;
import java.util.List;
import java.util.Map; import org.springframework.lang.Nullable; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtils { public static final ObjectMapper mapper = new ObjectMapper(); /**
* 对象转换为json字符串
* @param obj
* @return
*/
@Nullable
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
return null;
}
} @Nullable
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
return null;
}
} @Nullable
public static <E> List<E> toList(String json, Class<E> eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) { return null;
}
} @Nullable
public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
return null;
}
} @Nullable
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
return null;
}
} class User{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
super();
}
} public static void main(String[] args) {
String json="{\"namge\":\"zhuxinjun\",\"age\":\"21\"}";
Map<String, String> map = toMap(json, String.class, String.class);
System.out.println("map:"+map); String j="[{\"namge\":\"zhuxinjun\",\"age\":\"21\"},{\"namge\":\"yangyang\",\"age\":\"32\"}]";
List<Map<String, String>> maps = nativeRead(j, new TypeReference<List<Map<String, String>>>() {
});
for(Map<String,String> map1:maps){
System.out.println("map1"+map1);
}
} }
转载自: https://blog.****.net/u013089490/article/details/83585794