– Start
ObjectMapper 提供了下面的 readValue 方法,帮助我们很方便的从不同的数据源读取对象。
readValue(String src, ...)
readValue(File src, ...)
readValue(URL src, ...)
readValue(InputStream src, ...)
readValue(DataInput src, ...)
readValue(Reader src, ...)
readValue(byte[] src, ...)
ObjectMapper 也提供了下面的 writeValue 方法,帮助我们很方便的将对象输出到不同的目的地。
writeValueAsString(...)
writeValue(File desc, ...)
writeValue(File desc, ...)
writeValue(OutSteam desc, ...)
writeValue(DataOutput desc, ...)
writeValue(Writer desc, ...)
writeValueAsBytes(...)
我们还可以读取 JSON 到数组(Array),列表(List)和映射(Map)中,下面是三个简答的例子。
package shangbo.jackson.demo2;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// json 消息
String json = "[{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}, {\"firstname\":\"San\",\"lastname\":\"Zhang\"}]";
// 将 json 转成数组
Person[] people = objectMapper.readValue(json, Person[].class);
for(Person p: people) {
System.out.println(p);
}
}
}
package shangbo.jackson.demo3;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// json 消息
String json = "[{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}, {\"firstname\":\"San\",\"lastname\":\"Zhang\"}]";
// 将 json 转成列表
List<Person> people = objectMapper.readValue(json, new TypeReference<List<Person>>(){});
for(Person p: people) {
System.out.println(p);
}
}
}
package shangbo.jackson.demo4;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// json 消息
String json = "{\"firstname\":\"Bo\",\"lastname\":\"Shang\"}";
// 将 json 转成映射
Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});
System.out.println(map);
}
}
– 更多参见:Jackson 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-05-25
– Written by ShangBo on 2019-05-25
– End