MalformedJSONException:未终止的字符

时间:2019-05-28 06:13:23

标签: java android json hashmap gson

我从服务器收到以下JSON响应:

{
"addon_categories": [
{
  "addon_category_1_options": [
    {
      "addon_category_1_option_1_price": "2",
      "addon_category_1_option_1_ischecked": "no",
      "addon_category_1_option_1_title": "Extra"
    },
    {
      "addon_category_1_option_2_ischecked": "yes",
      "addon_category_1_option_2_price": "3",
      "addon_category_1_option_2_title": "Double"
    }
  ],
  "addon_category_1_type": "single",
  "addon_category_1_title": "Cheese"
},
{
  "addon_category_2_type": "multiple",
  "addon_category_2_options": [
    {
      "addon_category_2_option_1_ischecked": "yes",
      "addon_category_2_option_1_price": "0.5",
      "addon_category_2_option_1_title": "Extra Capsicum"
    },
    {
      "addon_category_2_option_2_title": "Extra Olives",
      "addon_category_2_option_2_ischecked": "no",
      "addon_category_2_option_2_price": "0.5"
    }
  ],
  "addon_category_2_title": "Others"
}
]
}

然后,我通过以下方式将其保存在首选项中:

TypeToken<ArrayList<HashMap<String, Object>>> token = new TypeToken<ArrayList<HashMap<String, Object>>>() {
    };
    String arrayString = new Gson().toJson(finalArray, token.getType());
    arrayString = arrayString.replace('=',':');
    Log.e("Printing final", arrayString);

    preferenceUtils.setAddOns(addon_id, arrayString);

然后,我再次访问它:

TypeToken<ArrayList<HashMap<String, Object>>> token = new TypeToken<ArrayList<HashMap<String, Object>>>() {
        };
        ArrayList finalArray = new Gson().fromJson(addons, token.getType());
        HashMap dict1 = (HashMap) finalArray.get(0);
        addOnsArray = (ArrayList<Object>) dict1.get("addon_categories");
        Log.e("final", addOnsArray.toString());

我确实得到了“ addonsArray”,但是,当我遍历这段代码时,我得到了错误:

for (int k = 0; k < addOnsArray.size(); k++) {
        HashMap<String, Object> addOn;
        if (addOnsArray.get(k) instanceof HashMap) {
            addOn = (HashMap<String, Object>) addOnsArray.get(k);
        } else {
            Gson gson = new Gson();
            String json = (addOnsArray.get(k)).toString();
            json = json.replace("=", ":");
            Log.e("Replace", json);
            TypeToken<HashMap<String, Object>> token = new TypeToken<HashMap<String, Object>>() {
            };
            addOn = gson.fromJson(json.trim(), token.getType());
        }

但是,我一开始并没有收到错误消息。当循环再次第二次运行时,出现此错误。因此,无法解决的错误是“ addon_category_2_option_1_title”。

我已经使用GSON来完成这两项操作。有人可以告诉我我在做什么错。

0 个答案:

没有答案