[英]Gson getAsString() fails if json array is empty
I'm using the Json library Gson in Java to parse json strings into CSV files. 我正在使用Java中的Json库Gson将json字符串解析为CSV文件。 Some of my json fields are null so I will have to check for that and add an empty string instead. 我的一些json字段为null,因此我必须检查该字段并添加一个空字符串。 Some of the fields in my json strings are arrays and some of them are empty. 我的json字符串中的某些字段是数组,而某些字段为空。 However, when these arrays are empty, the getAsString method in Gson fails with illeagStateException. 但是,当这些数组为空时,Gson中的getAsString方法失败,并带有illeagStateException。 Here is a runnable example: 这是一个可运行的示例:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
JsonObject message = new JsonParser().parse("{\"id\":null,\"text\":\"test\",\"types\":[]}").getAsJsonObject();
JsonElement element = message.get("types"); //now this is "[]"
String jsonElementAsString= element.isJsonNull() ? "" : element.getAsString(); //Here exception is thrown.
I'm already checking if json is null. 我已经在检查json是否为null。 What is a good workaround here? 有什么好的解决方法? I would like to avoid adding to much clutter in order to improve execution time. 我想避免增加太多混乱以缩短执行时间。 I could of course wrap it all in a try catch but that is expensive. 我当然可以将其全部包裹起来,但这很昂贵。
Since we know types
is an Array, the best way i would do is, first check types
is existed in JsonObject
由于我们知道types
是数组,所以我最好的方法是,首先检查types
存在于JsonObject
if(message.has("types")) //which avoids null pointer exception
Then get the types
as JsonArray
然后将types
作为JsonArray
JsonArray typesArray = message.getAsJsonArray("types");
And then use forEach
so you don't need to care if array is empty also 然后使用forEach
这样您就不必关心数组是否为空
typesArray.forEach(element->System.out.println(element));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.