JSONを解析しようとすると非常に奇妙なエラーが発生します。 が効果、ファイルは以下のように非常に簡単で単純なオブジェクトから構成されている:JSONを解析する際の問題
public static boolean isRegistered(int nmb) {
boolean toReturn = true;
JsonReader reader = null;
try {
reader = new JsonReader(new InputStreamReader(new URL("xxx").openConnection().getInputStream()));
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
Log.i("Next value", name);
switch (name) {
case "registered":
toReturn = reader.nextBoolean();
break;
case "firstname":
ProfileManager.getInstance().setFirstname(reader.nextString());
break;
case "name":
ProfileManager.getInstance().setName(reader.nextString());
break;
case "email":
break;
case "picture":
break;
case "username":
break;
}
}
reader.endObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return toReturn;
}
:
{
"registered":false,
"firstname":"xxx",
"name":"yyyy",
"email":"[email protected]",
"picture":"xxxxx.jpg",
"username":"xxxy"
}
このファイルを解析するために、私は、Android SDKの例に触発されて、次のコードを使用しました
実行を開始すると、実行時にエラーが発生します。
String name = reader.nextName();
エラーは、名前は期待されていますが、STRINGを取得しています。確かに、nextString()をnextString()に置き換え、反対のエラーを取得しました。文字列が必要ですがNAMEでした。私はpeek()メソッドのおかげで最初の値を調べることにしました。そして、最初の要素がNAMEであることがはっきりと分かります。だから私はループを使わずに手動でオブジェクトを読むことで非常に単純なことを試みました。どのように可能ですか?さらに、このコードを実行可能にするためには何を修正する必要がありますか?
ありがとうございました!
を提供作り付けのライブラリを使用してみては? – mariozawa
答えはありません。 1つの提案http://stackoverflow.com/a/18998203/3049065 org.json library ..を使用しています。 –
私はあなたの 'switch'(デフォルトを含む)のすべてのケースに対して適切な処理を追加したいと思います。現在の実装では、「メール」に遭遇した後に例外がスローされることが予想されます –