您的位置:首页 > 产品设计 > UI/UE

java 如何解析后台返回的key和value都未知的json

2018-03-25 01:43 656 查看
问题描述:

后台返回一段json对象,key、value都是动态且字段未知!如下所示,labels对象里面的key、value都是动态变化的。

{
bads: 0,
average: "8.3",
totalEvaluates: 6,
goodRate: "50%",
servedCompanies: "5",
goods: 3,
mediums: 3,
labels: {
安全专业性强: 6,
建议可行: 4,
对企业有帮助: 3,
服务态度好: 1
}
}


解决方案:

其他已知字段直接写进实体类的属性就行,那段动态的json对象需要使用
JsonElement
解析。JsonElement可以解析各种json格式。所以上述json可以写入下面的实体类:

public class CreditBean{
/**
* bads : 0
* average : 8.0
* totalEvaluates : 2
* goodRate : 50%
* servedCompanies :
* goods : 1
* mediums : 1
* labels :
*/

private int bads;
private String average;
private String totalEvaluates;
private String goodRate;
private String servedCompanies;
private int goods;
private int mediums;
private JsonElement labels;
}


请求下来的数据数据,可以这样操作:

JsonElement labels = credit.getLabels();//获取动态json元素类
Iterator<String> it = json.keys();//使用迭代器
while (it.hasNext()) {
String key = it.next();//获取key
int value = json.getInt(key);//获取value
Log.e("key-value","key="+key+" value="+value);
}


JsonElement(com.google.gson.JsonElement)简介:

该类是一个抽象类,代表着json串的某一个元素。这个元素可以是JsonObject , JsonArray, JsonPrimitive JsonNull等。

JsonElement提供了一系列的方法来判断当前的JsonElement类型:

/**
* provides check for verifying if this element is an array or not.
*
* @return true if this element is of type {@link JsonArray}, false otherwise.
*/
public boolean isJsonArray() {
return this instanceof JsonArray;
}

/**
* provides check for verifying if this element is a Json object or not.
*
* @return true if this element is of type {@link JsonObject}, false otherwise.
*/
public boolean isJsonObject() {
return this instanceof JsonObject;
}


JsonElement也提供了一系列的方法来获取对应类型的JsonElement:

/**
* convenience method to get this element as a {@link JsonObject}. If the element is of some
* other type, a {@link IllegalStateException} will result. Hence it is best to use this method
* after ensuring that this element is of the desired type by calling {@link #isJsonObject()}
* first.
*
* @return get this element as a {@link JsonObject}.
* @throws IllegalStateException if the element is of another type.
*/
public JsonObject getAsJsonObject() {
if (isJsonObject()) {
return (JsonObject) this;
}
throw new IllegalStateException("Not a JSON Object: " + this);
}

/**
* convenience method to get this element as a {@link JsonArray}. If the element is of some
* other type, a {@link IllegalStateException} will result. Hence it is best to use this method
* after ensuring that this element is of the desired type by calling {@link #isJsonArray()}
* first.
*
* @return get this element as a {@link JsonArray}.
* @throws IllegalStateException if the element is of another type.
*/
public JsonArray getAsJsonArray() {
if (isJsonArray()) {
return (JsonArray) this;
}
throw new IllegalStateException("This is not a JSON Array.");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: