、それはあなたがあなたの入力文字列内の重複を持っているし、(名前の変更、ドロップなど)、それらをどのように処理するかを選択することができます:これは、少なくともJSONオブジェクトが有効になるだろう。 Gsonライブラリを使用し、オブジェクトのシリアル化/逆シリアル化を担当するTypeAdapter
を登録する必要があります。それは次のようになります。
String str = "{\"innerkey1\":\"innervalue1\", \"innerkey2\":\"innervalue2\",\"innerkey1\":\"innervalue3\"}";
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> map = new GsonBuilder()
.registerTypeAdapter(mapType, new NoDuplicatesAdapter())
.create()
.fromJson(str, mapType);
map
のみ最初"innerkey1"
が含まれています:
class NoDuplicatesAdapter extends TypeAdapter<HashMap<String, String>> {
@Override
public void write(JsonWriter out, HashMap<String, String> value) throws IOException {
out.beginObject();
for (Map.Entry<String, String> e: value.entrySet()) {
out.name(e.getKey()).value(e.getValue());
}
out.endObject();
}
@Override
public HashMap<String, String> read(JsonReader in) throws IOException {
final HashMap<String, String> map = new HashMap<>();
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
// putting value to the map only if this key is not present;
// here you can actually find duplicate keys and decide what to do with them
map.putIfAbsent(name, in.nextString());
}
in.endObject();
return map;
}
}
をそれは最も複雑な部分だった、今、私たちはJSON
文字列を読み込む必要があります。
[解決するJSONExceptionの重複キー](https://stackoverflow.com/questions/4912386/resolve-jsonexception-duplicate-keys) – Lichtbringer
JSONが奇妙に見えます。 key1:value1はOKですが、配列として値を取得しています。キーはどこですか? –
@BuzzMoschettiここで、有効なjson文字列を探すことができます。 –