一、Json 报文格式如下:
二、获取 Json 报文中字段的内容
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ReadJsonValue_1_00_001 {
public static void main(String args[]) {
String test = "{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"objectID\":\"357\",\n" +
" \"geoPoints\":\n" +
" [\n" +
" {\n" +
" \"x\":504604.59802246094,\n" +
" \"y\":305569.9150390625\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"objectID\":\"358\",\n" +
" \"geoPoints\":\n" +
" [\n" +
" {\n" +
" \"x\":504602.2680053711,\n" +
" \"y\":305554.43603515625\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}\n";
System.out.println( test );
ObjectMapper mapper = new ObjectMapper();
JsonNode node = null;
try {
node = mapper.readTree( test );
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//将Json串以树状结构读入内存
JsonNode results = node.get("results");//得到results这个节点下的信息
System.out.println( "results.size() = " + results.size() );
for(int i = 0; i < results.size(); i++ ) //遍历results下的信息,size()函数可以得节点所包含的的信息的个数,类似于数组的长度
{
System.out.println( results.get(i).get("objectID").textValue() ); //读取节点下的某个子节点的值
JsonNode geoNumber = results.get(i).get("geoPoints");
System.out.println( "geoNumber() = " + geoNumber.size() );
for(int j = 0; j < geoNumber.size(); j++ ) //循环遍历子节点下的信息
{
System.out.println(geoNumber.get(j).get("x").doubleValue()+"--"+geoNumber.get(j).get("y").doubleValue());
}
}
}
}
三、读取结果为