2017-06-27 6 views
-2

私は、両方ともjsonファイルの値のペアを赤でキーするのに使用されていることがわかりました。私は上の検索JavaのJsonReaderとJsonParseの違い

try 
{ 
    InputStream isr=new FileInputStream(" 
     C:\\Users\\DELL\\Documents\\NetBeansProjects\\WaterNetwork 
     \\web\\kusha.json"); 
    JsonReader jsr=Json.createReader(isr); 
    JsonObject job=jsr.readObject(); 
    jsr.close(); 
    isr.close(); 
    System.out.println("Name is: "+job.getString("name")); 
} 

:JSONファイルのキーと値を読み取るために

try { 
    // read the json file 
    FileReader reader = new FileReader(filePath); 

    JSONParser jsonParser = new JSONParser(); 
    JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); 

    // get a String from the JSON object 
    String firstName = (String) jsonObject.get("firstname"); 
    System.out.println("The first name is: " + firstName); 

    // get a number from the JSON object 
    long id = (long) jsonObject.get("id"); 
    System.out.println("The id is: " + id); 

    // get an array from the JSON object 
    JSONArray lang= (JSONArray) jsonObject.get("languages"); 

    // take the elements of the json array 
    for(int i=0; i<lang.size(); i++){ 
     System.out.println("The " + i + " element of the array: "+lang.get(i)); 
    } 

    Iterator i = lang.iterator(); 

    // take each value from the json array separately 
    while (i.hasNext()) { 
     JSONObject innerObj = (JSONObject) i.next(); 
     System.out.println("language "+ innerObj.get("lang") + 
      " with level " + innerObj.get("knowledge")); 
    } 

    // handle a structure into the json object 
    JSONObject structure = (JSONObject) jsonObject.get("job"); 
    System.out.println("Into job structure, name: " + structure.get("name")); 
} 

そしてJsonReaderの使用:JsonParserの使用は、キーJSONファイルの値を読み込むための

例えば:今まで何の役に立つ答えも得られていない。ですから、JsonReaderとJavaのJsonParserとの違いについての完全な説明が必要です。

+0

名前の通り、読者はループ内で1行ずつ読むことができます。パーサーはJSONオブジェクト全体をJava配列やオブジェクトなどに解析します – Casper

答えて

0

名前からわかるように、JsonReaderは、文字列またはストリームとして存在するJSONオブジェクトを識別して読み取ってから、適切なJSONオブジェクトに変換して戻します。

あなたは、あなたがJSONReaderオブジェクトから取得する可能性があると言うJSONオブジェクトから値を抽出するためにゲッターを使用して、つまり、オブジェクトの下の値と配列を読み取ることができないJSONオブジェクトを解析できませんすることができます。

ここではインターフェイスについて話しているので、これはすべて抽象です。 両方の機能を利用して、わかりやすくなりました。

関連する問題