1

I have this JSON:

{
    "username": [
        "A user with that username already exists."
    ],
    "ruc": [
        "user with this ruc already exists."
    ],
    "code": [
        "user with this code already exists."
    ],
    "document_number": [
        "user with this document number already exists."
    ]
}

The name of the properties will be dynamic and the length of the JSON too. I'm using GSON tool and I create a POJO but without a name, I cant reference to this, that's, why I received that myError instance, is null. This is my POJO

public class MyError {
    public Map<String, Object> message = new HashMap<>();
}

And this is my GSON code

myError = new Gson().fromJson(response.errorBody().string(), MyError.class);

And I want to show a message for every item like this:

for (String key : myError.message.keySet()) {
    Utils.showToast(getBaseContext(), "Message: " + myError.message.get(key) + " Field: " + key);
}

2 Answers2

1

You can try to use this:

Map myError = new Gson().fromJson(s, Map.class);

Or if you want to use your class json should look like:

{ "message": { "username": [ "A user with that username already exists." ], "ruc": [ "user with this ruc already exists." ], "code": [ "user with this code already exists." ], "document_number": [ "user with this document number already exists." ] } }

Yegor Babarykin
  • 705
  • 3
  • 12
0

Consider using Gson and java native JsonParser.

Remario
  • 3,813
  • 2
  • 18
  • 25