【记录002】Json字符串转换
实践中的一些小记录
- 将对象转换成为JSON字符串
/**
* 将对象转换成为JSON字符串
* @param t
* @param <T>
* @return
*/
public static <T>String toString(T t){
return JSON.toJSONString(t, SerializerFeature.DisableCircularReferenceDetect);
}
2.将JSON字符串转换成对象
/**\
* 将JSON字符串转换成对象
* @param jsonString
* @param clazz
* @param <T>
* @return
*/
public static <T>T toObject(String jsonString,Class<T> clazz){
return JSON.parseObject(jsonString,clazz);
}
- 将JSON字符串转换成集合
/**
* 将JSON字符串转换成集合
* @param jsonString
* @param clazz
* @param <T>
* @return
*/
public static <T>List<T> toList(String jsonString,Class<T> clazz){
return JSON.parseArray(jsonString,clazz);
}
/**
* 将JSON字符串转换成集合
* @param jsonString
* @param clazz
* @param <T>
* @return
*/
public static <T>List<T> jsonToList(String jsonString,Class<T> clazz){
ObjectMapper objMap=new ObjectMapper();
JavaType javaType=objMap.getTypeFactory().constructParametricType(List.class,clazz);
List<T> list= null;
try {
list = objMap.readValue(jsonString,javaType);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
- bean对象
package demo.bean;
/**
* bean对象
*/
public class beanType {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "beanType{" +
"id='" + id + '\'' +
", text='" + text + '\'' +
'}';
}
}
- 测试方法
public static void main(String[] args){
String jsonString="[{\"id\":\"1234\",\"text\":\"数学\"},{\"id\":\"4567\",\"text\":\"语文\"}]";
List<beanType> list=JsonUtil.toList(jsonString,beanType.class);
System.out.println(list);
}
- 通过Maven管理加包,pom.xml配置如下:
<!--阿里巴巴JSON组件-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
- 主要应用到的包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo.bean.beanType;
import java.io.IOException;
import java.util.List;