Gson反序列化混合对象类型

时间:2015-05-15 13:51:44

标签: android json gson

我有一个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
      }
    ]

我有一个类,其结构如下:

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;
        }
    }

我使用GSON绑定这些,我能够绑定2个JsonArrays。

我还可以使用How can I convert JSON to a HashMap using Gson?

对jsonArrays的动态属性进行反序列化

但在这种情况下,我不知道如何获取动态属性, 我的计划应该是将动态属性转换为hashmap,但是2个jsonArrays正在阻碍。

感谢您的帮助,

1 个答案:

答案 0 :(得分:0)

由于这篇文章Using GSON to parse array with multiple types,我已经找到了如何使用GSON自定义反序列化器,此帖也是java collections - keyset() vs entrySet() in map 我所做的是创建这个自定义反序列化器:

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;
    }
}

然后像这样使用它:

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

顺便说一句, AccountRepresentative是一个内部类,AccountRepresentative中的两个数组总是在JSON中,只有属性是动态的。

我以为我无法解析内部版本并为AccountDetailModel本身创建自定义反序列化器,但我尝试为AccountRepresentative创建反序列化器,它很好:)