0

すべての Json 配列が同じ名前を持つ Json ファイルを解析したい:

[
   {
      "mobileMachine":{
         "condition":"GOOD",
         "document":"a",
         "idNr":"ce4f5a276a55023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e"
      }
   },
   {
      "mobileMachine":{
         "condition":"GOOD",
         "document":"b",
         "idNr":"ce4f5a276a8e023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb217e"
      }
   },
   ...
]

だからここに私の小さなコードがあります:

JSONArray json = new JSONArray(urlwhereIGetTheJson);
for (int count = 0; count < json.length(); count++) {
    JSONObject obj = json.getJSONObject(count);

    String condition = obj.getString("condition");
    String document = obj.getString("document");
    String idNr = obj.getString("idNr");

    db.addMachine(new MachineAdapter(condition, document, idNr));
}

JSON ファイルを正しく解析する方法を教えていただければ幸いです。ありがとうございました

JSON ファイルを編集できません。(ファイルには 300 以上のモバイルマシンが含まれています。私はこれを短縮しました)。

(私の英語でごめんなさい)

4

2 に答える 2

0

に変更します

JSONArray json = new JSONArray(jsonString);
for (int count = 0; count < json.length(); count++) {
   JSONObject obj = json.getJSONObject(count).getJSONObject("mobileMachine");


   String condition = obj.getString("condition");
   String document = obj.getString("document");
   String idNr = obj.getString("idNr");

   db.addMachine(new MachineAdapter(condition, document, idNr));
}

「mobileMachine」を忘れました。

于 2013-10-28T13:11:30.137 に答える
0

編集:new JSONArray()コンストラクターを正しく使用していません。ドキュメントをご覧ください。そこにURLを直接渡すことはできません。最初にそれを取得してから、json をコンストラクターに渡す必要があります。

次のコードは、やりたいことを実行します。

JSONArray jsonArray = new JSONArray(json);
int numMachines = jsonArray.length();

for(int i=0; i<numMachines; i++){
    JSONObject obj = jsonArray.getJSONObject(i);

    JSONObject machine = obj.getJSONObject("mobileMachine");
    String condition = machine.getString("condition");
    String document = machine.getString("document");
    String idNr = machine.getString("idNr");

    db.addMachine(new MachineAdapter(condition, document, idNr));
}

"mobileMachine" json オブジェクトを取得するのを忘れて、直接 condition/document/idNr にアクセスしようとしました。

XML を制御できる場合は、「mobileMachine」ノードを削除して、XML を小さくすることができます。

[
   {
       "condition":"GOOD",
       "document":"a",
       "idNr":"ce4f5a276a55023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e"
   },
   {
       "condition":"GOOD",
       "document":"b",
       "idNr":"ce4f5a276a8e023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb217e"
   },
   ...
]
于 2013-10-28T13:12:11.577 に答える