2017-08-11 2 views
0

json-simpleを使用してjsonオブジェクトの配列を解析する際に問題が発生しています。ファイルからオブジェクトの配列を解析するためにJson-simpleを使用する

reportオブジェクトの次の配列を考える:次のコードで

[ 
    { 
    "title": "Test Object 1", 
    "description": "complicated description...", 
    "products": null, 
    "formats": ["csv"] 
    }, 
    { 
    "title": "Test Object 2", 
    "description": "foo bar baz", 
    "products": ["foo"], 
    "formats": ["csv", "pdf", "tsv", "txt", "xlsx"] 
    }, 
    { 
    "title": "Test Object 3", 
    "description": "Lorem Ipsum stuff...", 
    "products": null, 
    "formats": ["pdf", "xlsx"] 
    } 
] 

、ファイルから読み込んだ後、どのように私は操作を実行するために、アレイ内の各オブジェクトを反復処理することができますか?

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 

public class JsonReader { 

public static void main(String[] args) { 

    JSONParser parser = new JSONParser(); 

    try { 
     Object obj = parser.parse(new FileReader("sample.json")); 

     //convert object to JSONObject 
     JSONObject jsonObject = (JSONObject) obj; 

     //reading the string 
     String title = (String) jsonObject.get("title"); 
     String description = (String) jsonObject.get("description"); 

     //Reading an array 
     JSONArray products = (JSONArray) jsonObject.get("products"); 
     JSONArray formats = (JSONArray) jsonObject.get("formats"); 

     //Log values 
     System.out.println("title: " + title); 
     System.out.println("description: " + description); 

     if (products != null) { 
      for (Object product : products) { 
       System.out.println("\t" + product.toString()); 
      } 
     } else { 
      System.out.println("no products"); 
     } 

     if (formats != null) { 
      for (Object format : formats) { 
       System.out.println("\t" + format.toString()); 
      } 
     } else { 
      System.out.println("no formats"); 
     } 

    } catch (FileNotFoundException fe) { 
     fe.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

デバッガを実行しているが、jsonObjectが配列を格納し、それを取得する方法イムわからないようです。 JSONObjectが反復可能ではないため、各ループに対してaを作成しても動作しないようです。

+0

それが表示されます。解析したいJSONはJSONArrayであり、単一のJSONObjectではありません。それが助けば。 – drelliot

答えて

2

あなたのJSONはJSON標準に関しては有効ではないと思います(JSON.org参照)。 JSONは '{'で始まり、 '}'で終わる必要があります。私はキーが欠けているので、配列が標準的な方法でアクセスできるとは思わない。それが可能であるならば、あなたは(あなたのコードでは、あなたのJSON文字列にまたはちょうどこのCONCAT)の間、あなたのJSONを置く必要があります。

{ "array": 
    //yourJson 
} 

次に、あなたのようなものでアレイをacsessできます

JSONArray array = (JSONArray) jsonObject.get("array"); 
Iterator iter = array.iterator(); 


while (iter.hasNext()) { 
     System.out.println((iter.next()).get("title")); 
    } 
関連する問題