instanceof不适用于JSON对象-为什么?

问题描述 投票:0回答:1

check this link for the response Hi在下面的代码键名称中,值的作用是对象和字符串。要检查名称。如果名称与之匹配,则应检查两个条件值是对象还是字符串。

如果值是对象,则条件应执行,否则条件应执行。但不会进行任何循环。

谁能告诉我我在哪里做错了

Json回应:

{
  "name": "account_id",
  "value": {
      "value": "11x52927",
      "label": "Alfa HOSPITAL"
  },
  "label": "Account Name",
  "uitype": "51",
  "type": {
      "defaultValue": null
  }
},
{
  "name": "cf_905",
  "value": "Intensive Care Medicine",
  "label": "Specialization",
  "uitype": "16",
  "type": {
      "defaultValue": null
  }
},

Contacts.java:

for (SynFields synFields1: synFields) {

    String name = synFields1.getName();

    if (name.equals("account_id")) {
        Object values = synFields1.getValue();

        try {

            if (values == JSONObject.NULL) {
                // Handle NULL
            } else if (values instanceof JSONObject) {
                JSONObject jsonObject1 = null;
                try {
                    jsonObject1 = new
                    JSONObject(String.valueOf(synFields1.getValue()));
                    String value = ((JSONObject) values).getString("value");
                    String labels = ((JSONObject) values).getString("label");

                    account_names.add(labels);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                String value_accounts = String.valueOf(synFields1.getValue());
                account_names.add(value_accounts);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

SynField.java:

public class SynFields {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("value")
    @Expose
    private Object value;

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    @SerializedName("label")
    @Expose
    private String label;

}
android instanceof
1个回答
1
投票
尝试这样

try { if (values == Null) { // Handle null object continue; } if(values instanceof String){ String value_accounts = String.valueOf(values); account_names.add(value_accounts); }else{ Gson gson = new Gson(); JSONObject jsonObject = new JSONObject(gson.toJson(values)); // convert Object to JSONObject String value = jsonObject.getString("value"); String labels = jsonObject.getString("label"); account_names.add(labels); } } catch (JSONException e) { e.printStackTrace(); }

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.