Nataliia.dev
Nataliia.dev

Reputation: 2972

Parse json object usng gson with changeable field

I have json request which can consist the next parameter, initially I did not know the type of the parameter, it can be :

"message":"one message"

or

"message":{"part_one":"first part of message","part_two":"second part of message"}

I try to parse this field to string

String message;

and to custom Message object

Message message; 

class Message{
String part_one;
String part_two;
}

Also I try to use List, Map and other, but i have parsing error when the type does not match.

How can i build parsing output object for fromJson() function (gson library)? Please help.

Upvotes: 0

Views: 1747

Answers (2)

Nataliia.dev
Nataliia.dev

Reputation: 2972

My last solution - customize

JsonDeserializer

Json message:

1) success message

{"data": ["success"],
       "message": "message_text"
    }

2) error message

{"message": { "name": ["message_text"], "email": ["message_text"], "subject": ["message_text"], "body": ["message_text"] }}

Maybe it can help someone.

 public static class GeneralResponceDeserializer implements JsonDeserializer {

    @Override
    public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jobject = (JsonObject) jsonElement;
        Gson googleJson = new Gson();
        ArrayList<String> dataList = null;
        if (jobject != null && jobject.get("data") != null) {
            JsonArray dataArray = jobject.get("data").getAsJsonArray();
            dataList =  googleJson.fromJson(dataArray, new TypeToken<List<String>>(){}.getType());
        }
        String message = null;
        Message messageObject = null;
        if (jobject != null && jobject.get("message") != null) {
            try {
                message = jobject.get("message").getAsString();
            } catch (UnsupportedOperationException e) {
                JsonElement messageObjectJson = (JsonObject) jobject.get("message").getAsJsonObject();
                JsonObject jMessageobject = (JsonObject) messageObjectJson;
                if (jMessageobject != null) {
                    JsonArray name = jMessageobject.getAsJsonArray("name");
                    JsonArray subject = jMessageobject.getAsJsonArray("subject");
                    JsonArray body = jMessageobject.getAsJsonArray("body");
                    JsonArray email = jMessageobject.getAsJsonArray("email");
                    ArrayList<String> nameDataList = null;
                    ArrayList<String> subjectDataList = null;
                    ArrayList<String> bodyDataList = null;
                    ArrayList<String> emailDataList = null;
                    if (name != null) {
                        nameDataList =  googleJson.fromJson(name, new TypeToken<List<String>>(){}.getType());
                    }
                    if (subject != null) {
                        subjectDataList =  googleJson.fromJson(subject, new TypeToken<List<String>>(){}.getType());
                    }
                    if (body != null) {
                        bodyDataList =  googleJson.fromJson(body, new TypeToken<List<String>>(){}.getType());
                    }
                    if (email != null) {
                        emailDataList = googleJson.fromJson(email, new TypeToken<List<String>>(){}.getType());
                    }
                    messageObject = new Message(nameDataList, subjectDataList, bodyDataList, emailDataList);
                }
            }
        }


        return new GeneralResponceObject(dataList, message, messageObject);
    }
}

Upvotes: 0

Moog
Moog

Reputation: 10193

GSON is rather in-depth for this trivial example however there is an extensive GSON user-guide should you wish to pursue this method.

The simple answer though is to use he JSONObject class that is built-in to the android SDK. There is a full JSON tutorial which should help.

Simply:

JSONObject myObject = new JSONObject(myResponseString);

There are several function to then extract data from the object which you can use in your function or response object constructor to simplify your codebase.

If you have an array of objects then use JSONArray

Most importantly, read the documentation on http://developer.android.com

UDPATE

You can use the optJSONObject method to detect if the "message" value is an object rather than a simple string.

To use your example class add a method to you message class:

public static Message fromJson(string jsonString) throws JSONException
{

    JSONOBject jsonObject = new JSONObject(jsonString);

    Message message = new Message(); //create our return object

    JsonObject messageObject = jsonObject.optJSONObject("message");

    if(messageObject!=null)
    {
        //get our member variables from the messageObject
        message.part_one = messageObject.getString("part_one");
        message.part_two = messageObject.getString("part_two");
    }
    else
    {   // it's a simple string so just get the string from jsonObject
        message.part_one = jsonObject.getString("message");
    }
    return message;
}

You should, of course, add exception handling and perhaps throw a custom exception or return null if the parse fails.

Upvotes: 2

Related Questions