2016-07-11 3 views
0
{ 
    "blogURL": "http://crunchify.com", 
    "twitter": "http://twitter.com/Crunchify", 
    "social": [{ 
     "id": "1", 
     "message": "hi" 

    }, 
    { 
     "id": "2", 
     "message": "hello" 

    }] 
} 

아래 코드를 사용하여 위의 .txt 파일을 읽으려고합니다.배열을 사용하여 json 객체 읽기

package com.srishti.space_om; 

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

import org.json.JSONException; 
import org.json.JSONObject; 



public class SPACE_Parse { 
    public static void main(String[] args) throws FileNotFoundException, JSONException { 
     String jsonData = ""; 
     BufferedReader br = null; 
     try { 
      String line; 
      br = new BufferedReader(new FileReader("C:/Users/Rachana/workspace/SPACEOM/WebContent/Data/Parse_JSON.txt")); 
      while ((line = br.readLine()) != null) { 
       jsonData += line + "\n"; 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null) 
        br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
     // System.out.println("File Content: \n" + jsonData); 
     JSONObject obj = new JSONObject(jsonData); 
     System.out.println("blogURL: " + obj.getString("blogURL")); 
     System.out.println("twitter: " + obj.getString("twitter")); 

    } 
} 

나는 blogURL과 트위터하지만 즉, 첫 번째 사회적 배열을 읽을 수있는 방법을, 내가 사회 [0] [ID]를 읽고 (1)과 사회 [1] [ID]를 얻을 수 있어야 읽을 수 있어요 = 그런 2.

+0

. (JSONArray) obj.get ("social")) get (0) .get ("id")'(가정 할 때' JSONArray'가 존재하고'JSONObject'를 확장합니다). – Thomas

답변

0

떨어지게 :

배열을 처리하는`JSONArray` 클래스는 대부분의 아마있다
JSONArray array = obj.getJSONArray("social"); 
for (int i = 0; i < array.length(); i++) { 
    JSONObject row = array.getJSONObject(i); 
    id = row.getInt("id"); 
    message= row.getString("message"); 
} 
관련 문제