Intereting Posts
   

使用Retrofit解析动态密钥Json字符串

我正在尝试解析以下动态密钥Json String。

"report":{ "data":{ "results":{ "558952cca6d73d7d81c2eb9d":{ "Max":-1, "Min":-1, "Slope":-1, }, "558ce148a6d73d7d81c2fa8a":{ "Max":-2, "Min":-1, "Slope":-2, } } } } 

以下我试图获取数据,但在解析上一个动态json String时得到错误。

  public class Report { @SerializedName("data") @Expose private Data data; public Data getData() { return data; } public void setData(Data data) { this.data = data; } @Override public String toString() { return "Report{" + "data=" + data + '}'; } } public class Data { @SerializedName("results") @Expose private ResultInside result; public ResultInside getResult() { return result; } public void setResult(ResultInside result) { this.result = result; } } public class ResultInside { /*@SerializedName("results") @Expose*/ private Map elemDetails = new HashMap(); public Map getElemDetails() { return elemDetails; } public void setElemDetails(Map elemDetails) { this.elemDetails = elemDetails; } } 

任何建议如何在这种情况下解析!

您的resultInside类正在添加JSON中不存在的额外对象层。 尝试将地图移动到Dataresults字段。

 public class Data { @SerializedName("results") @Expose private Map result; //.... } 

更好的方法是:

 ---------------------- public class Report { @SerializedName("data") @Expose private Data data; ---------------------- public class Data { public HashMap dataValues; public Data() { this.dataVaues = new HashMap<>(); } } ----------------------------- 

然后,创建一个像这样的Parser类:

 public class DataParser implements JsonDeserializer { @Override public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Data result = new Data(); try { final HashMap map = readServiceUrlMap(json.getAsJsonObject()); if(map != null) { result.dataValues = map; } }catch (JsonSyntaxException ex){ return null; } return result; } private HashMap readServiceUrlMap(final JsonObject jsonObject) throws JsonSyntaxException { if(jsonObject == null) { return null; } Gson gson = new Gson(); HashMap products = new HashMap<>(); for (Map.Entry entry : jsonObject.entrySet()) { String key = entry.getKey(); DataValues value = gson.fromJson(entry.getValue(), DataValues.class); products.put(key, value); } return products; } ---------------------------------------------- 

之后,在您的ApiClient类中键入它

 public class ApiClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if(retrofit == null) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Data.class, new DataParser()); retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create())) .build(); 

我希望这会对某人有所帮助