1

I have a JSON:

"account_representatives": [
      {
        "Sales Person": 1307,
        "default_ticket_assignments": [
          ""
        ],
        "Primary Account Manager": 1307,
        "Secondary Support-3": 1151,
        "Relationship Mgr": 1307,
        "authorized_resources": [
          ""
        ],
        "Technical Account Manager": 164
      }
    ]

and I have a class whose structure is like this:

public class AccountRepresentative {

        @SerializedName("authorized_resources")
        @Expose
        private List<String> authorizedResources = new ArrayList<String>();
        @SerializedName("default_ticket_assignments")
        @Expose
        private List<String> defaultTicketAssignments = new ArrayList<String>();
        @Expose
        private Map<String, String> repFields;

        /**
         * @return The authorizedResources
         */
        public List<String> getAuthorizedResources() {
            return authorizedResources;
        }

        /**
         * @param authorizedResources The authorized_resources
         */
        public void setAuthorizedResources(List<String> authorizedResources) {
            this.authorizedResources = authorizedResources;
        }

        /**
         * @return The defaultTicketAssignments
         */
        public List<String> getDefaultTicketAssignments() {
            return defaultTicketAssignments;
        }

        /**
         * @param defaultTicketAssignments The default_ticket_assignments
         */
        public void setDefaultTicketAssignments(List<String> defaultTicketAssignments) {
            this.defaultTicketAssignments = defaultTicketAssignments;
        }

        /**
         *
         * @return the dynamic jsonObjects
         */
        public Map<String, String> getRepFields() {
            return repFields;
        }

        /**
         * @param repFields The repFields
         */
        public void setRepFields(Map<String, String> repFields) {
            this.repFields = repFields;
        }
    }

I'm using GSON to bind these, I'm able to bind the 2 JsonArrays.

I can also deserialized dynamic properties w/o the jsonArrays by using How can I convert JSON to a HashMap using Gson?,

but in this case, I have no idea how to get the dynamic properties, My plan supposedly is to turn the dynamic properties into hashmap, but the 2 jsonArrays are in the way.

Thanks for the help,

Community
  • 1
  • 1

1 Answers1

0

I have found out how to use the GSON custom deserializer thanks to this post, Using GSON to parse array with multiple types, also this post, java collections - keyset() vs entrySet() in map What I did is to create this custom deserializer:

package com.xxx.xyz.models;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class AccountRepresentativeDeserializer implements JsonDeserializer<AccountDetailsModel.AccountRepresentative> {
    @Override
    public AccountDetailsModel.AccountRepresentative deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Log.v("AUTHORIZED REP ", json.toString());
        AccountDetailsModel.AccountRepresentative accountRep = new AccountDetailsModel().new AccountRepresentative();
        JsonObject jObject = json.getAsJsonObject();
        Set<Entry<String, JsonElement>> items = jObject.entrySet();
        Iterator<Entry<String, JsonElement>> it = items.iterator();
        Map<String, String> repFields = new HashMap<>();

        while (it.hasNext()) {
            Entry<String, JsonElement> i = it.next();
            if (i.getKey().equals("default_ticket_assignments")) {
                ArrayList<String> defaultTicketAssignments = new ArrayList<>();
                JsonArray defTicketAssignment = i.getValue().getAsJsonArray();
                Iterator<JsonElement> defTicketIterator = defTicketAssignment.iterator();

                while (defTicketIterator.hasNext()) {
                    JsonElement defTicketItem = defTicketIterator.next();
                    defaultTicketAssignments.add(defTicketItem.getAsString());
                }
                accountRep.setDefaultTicketAssignments(defaultTicketAssignments);
            } else if (i.getKey().equals("authorized_resources")) {
                ArrayList<String> authorizedResources = new ArrayList<>();
                JsonArray authorizedRes = i.getValue().getAsJsonArray();
                Iterator<JsonElement> authorizedResIterator = authorizedRes.iterator();

                while (authorizedResIterator.hasNext()) {
                    JsonElement defTicketItem = authorizedResIterator.next();
                    authorizedResources.add(defTicketItem.getAsString());
                }
                accountRep.setAuthorizedResources(authorizedResources);
            } else {
                repFields.put(i.getKey(), i.getValue().getAsString());
            }
        }
        accountRep.setRepFields(repFields);
        return accountRep;
    }
}

Then use it like so:

Gson gson = new GsonBuilder().registerTypeAdapter(AccountDetailsModel.AccountRepresentative.class, new AccountRepresentativeDeserializer()).create();
                        AccountDetailsModel result = gson.fromJson(strResult, AccountDetailsModel.class);

btw, the AccountRepresentative is an inner class and the two arrays inside the AccountRepresentative are always in the JSON, only the properties are dynamic.

I thought I won't be able to parse the internal one and make the custom deserializer for the AccountDetailModel itself, but I tried to create the deserializer for the AccountRepresentative, and it went fine :)

Community
  • 1
  • 1
  • 1
    You might like to check out this link: https://futurestud.io/tutorials/gson-advanced-customizing-de-serialization-and-adding-instance-creators-via-jsonadapter which addresses the same problem, but allows one to remove some of the boilerplate using the `@JsonAdapter(YourDeserialiser.class)` annotation, which you add to your model class. In this way you don't need to register your deserialiser with the builder. – Bill Naylor Apr 24 '20 at 17:02