Java 讀取 Json格式的 內容
阿新 • • 發佈:2018-11-22
一、Json 報文格式如下:
二、獲取 Json 報文中欄位的內容
1 import java.io.IOException; 2 import com.fasterxml.jackson.core.JsonProcessingException; 3 import com.fasterxml.jackson.databind.JsonNode; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 6public class ReadJsonValue_1_00_001 { 7 8 public static void main(String args[]) { 9 10 String test = "{\n" + 11 " \"results\":\n" + 12 " [\n" + 13 " {\n" + 14 " \"objectID\":\"357\",\n" + 15 " \"geoPoints\":\n" + 16" [\n" + 17 " {\n" + 18 " \"x\":504604.59802246094,\n" + 19 " \"y\":305569.9150390625\n" + 20 " }\n" + 21 " ]\n" + 22 " },\n" + 23 " {\n" + 24 " \"objectID\":\"358\",\n" + 25" \"geoPoints\":\n" + 26 " [\n" + 27 " {\n" + 28 " \"x\":504602.2680053711,\n" + 29 " \"y\":305554.43603515625\n" + 30 " }\n" + 31 " ]\n" + 32 " }\n" + 33 " ]\n" + 34 "}\n"; 35 36 System.out.println( test ); 37 38 ObjectMapper mapper = new ObjectMapper(); 39 JsonNode node = null; 40 try { 41 node = mapper.readTree( test ); 42 } catch (JsonProcessingException e) { 43 e.printStackTrace(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 48 //將Json串以樹狀結構讀入記憶體 49 JsonNode results = node.get("results");//得到results這個節點下的資訊 50 System.out.println( "results.size() = " + results.size() ); 51 52 for(int i = 0; i < results.size(); i++ ) //遍歷results下的資訊,size()函式可以得節點所包含的的資訊的個數,類似於陣列的長度 53 { 54 System.out.println( results.get(i).get("objectID").textValue() ); //讀取節點下的某個子節點的值 55 56 JsonNode geoNumber = results.get(i).get("geoPoints"); 57 System.out.println( "geoNumber() = " + geoNumber.size() ); 58 for(int j = 0; j < geoNumber.size(); j++ ) //迴圈遍歷子節點下的資訊 59 { 60 System.out.println(geoNumber.get(j).get("x").doubleValue()+"--"+geoNumber.get(j).get("y").doubleValue()); 61 } 62 } 63 } 64 65 }
三、讀取結果為