对象值使用JSON解析显示具有相同名称的对象和字符串

时间:2020-02-04 07:59:43

标签: android json

您好,以下内容不在JSON对象块的内部,并且不返回任何内容。在以下响应中,如果值是JSON对象,则应返回值。如果不是对象,则应进入else块并返回字符串。

有人可以帮助我解决问题吗?

响应:

{
  "name": "account_id",
  "value": {
      "value": "11x52925",
      "label": "VS Hospital"
  },
  "label": "Account Name",
  "uitype": "51",
  "type": {
      "defaultValue": null
  }
},

accounts.java:

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

   try {

       if (values instanceof JSONObject) {
           JSONObject jsonObject1 = new
             JSONObject(String.valueOf(synFields1.getValue()));
           String value = jsonObject1.getString("label");
           account_name.add(value);
       }
       else if (values instanceof String) {
           //here, you get a string

           //account_name.addAll(value);
           String value_names = String.valueOf(synFields1.getValue());
           String value_label = String.valueOf(synFields1.getLabel());
           // Log.e("account_name", 
           String.valueOf(account_name.add(value)));
           account_name.add(value_label );

           //account_name.add(value);
       }

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

预期产量:VS医院

1 个答案:

答案 0 :(得分:0)

使用GSON制作对象 这是经过测试的代码

Gson g = new Gson();
        String jsonString = "{\"name\": \"account_id\",  \"value\": {      \"value\": \"11x52925\",     \"label\":\"VSHospital\"  },\"label\":\"Account Name\",  \"uitype\": \"51\",  \"type\": {      \"defaultValue\": null  }}";
        Example p = g.fromJson(jsonString, Example.class);
        Log.d("dsds",p.getValue().getLabel() );

使用http://www.jsonschema2pojo.org/

进行POJO

在Gradle中添加GSON

implementation 'com.google.code.gson:gson:2.8.6'
相关问题