android - 对象值显示使用 JSON 解析对象和具有相同名称的字符串
问题描述
嗨,在下面不进入 JSON 对象块并且不返回任何内容。在下面的响应中,如果值是 JSON 对象,它应该返回值。如果不是对象,它应该转到 else 块并返回字符串。
谁能帮我解决这个问题?
回复:
{
"name": "account_id",
"value": {
"value": "11x52925",
"label": "VS Hospital"
},
"label": "Account Name",
"uitype": "51",
"type": {
"defaultValue": null
}
},
帐户.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医院
解决方案
此处使用 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'
推荐阅读
- java - Java:使用 javax.json.JsonObject 和 RESTEasy 嵌入式服务器时 JSON 模式错误
- django - django下载多个字节流文件
- c# - 使用 C# 使用 Dapper Plus 进行批量插入的最快方法
- rx-java - 如果 observable.filter().first() 什么都不返回,如何返回 Observable.empty()?
- mysql - mySQL WooCommerce - 产品、类别、价格和数量表
- tinymce - Umbraco Tinymce 为空标签添加空格
- heroku - Heroku 上的 Puppeteer 代理
- mongodb - MongoDB聚合问题
- c# - .NET Core Framework 2.1 中的 ReST 返回单个记录
- android - Android应用程序录制音频不允许whatsapp发送音频