2016-07-11 11 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")); 

    } 
} 

[ID] [1]私はblogURLやTwitterを読み取ることができていますが、どのように私は最初の社会的な配列、すなわちを読むことができます、私は社会的読み取ることができなければならない[0] [ID]と1や社会を取得そのような= 2

+0

配列を扱う 'JSONArray'クラスはおそらくあります。 (JSONArray)obj.get( "social"))。get(0).get( "id") '(仮に' JSONArray'が存在し、 'JSONObject'を拡張します)。 – Thomas

答えて

0

なめらか:

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"); 
} 
関連する問題