“{“name”:“”,"pwd":""},{“name”:“”,“pwd”:“”}” 类似于这样的字符串有木有办法用jackson转成json数组,求大神指导!
------解决思路----------------------
[{"name":"xxx","pwd":"xxx"},{"name":"xx","pwd":"xx"}]你直接转换呀,readvalue
------解决思路----------------------
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class TestJackson {
private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("Tom");
p1.setPwd("123");
Person p2 = new Person();
p2.setName("Jerry");
p2.setPwd("321");
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
// 对象转json字符串
String strJson = convertObjectToString(list);
System.out.println(strJson);
// json字符串转对象
List<Person> list2 = parseJson(strJson, new TypeReference<List<Person>>() {
});
System.out.println(list == list2);// false表示返回的是不同的对象
}
@SuppressWarnings("unchecked")
public static <T> T parseJson(String jsonString, TypeReference<T> typeOfT) {
T t = null;
try {
t = (T) JACKSON_MAPPER.readValue(jsonString, typeOfT);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return t;
}
public static String convertObjectToString(Object obj) {
StringWriter w = new StringWriter();
String jsonValue = null;
try {
JACKSON_MAPPER.writeValue(w, obj);
jsonValue = w.toString();
} catch (JsonParseException e) {
// 异常时,记录日志,不中断程序
e.printStackTrace();
} catch (JsonMappingException e) {
// 异常时,记录日志,不中断程序
e.printStackTrace();
} catch (IOException e) {
// 异常时,记录日志,不中断程序
e.printStackTrace();
}
return jsonValue;
}
}
class Person {
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
------解决思路----------------------
你是想转换成JSONArray对象?jackson的包肯定有提供对应的方法,你看看是不是构造方法就能传String进去。
我现在用fastjson,它的方法是JSONArray s = JSON.parseArray(str);