大家好,又见面了,我是你们的朋友全栈君。
异常信息:
Exception in thread “main” java.lang.IllegalStateException: Not a JSON Object: null at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:84)
Gson doesn’t serialize anonymous classes. Use Map.of to create maps, not subclasses. 当拿到的map是通过初始化赋值得到的时,你可以通过添加type参数来进行Json格式转换。
code:
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test3 {
private static Gson gson = new Gson();
private static JsonParser jsonParser = new JsonParser();
public static final Map<String, String> map = new HashMap<String, String>(){
{
put("111", "22");
put("11", "11");
}
};
public static void main(String[] args) {
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = Maps.newHashMap();
map1.put("11","11");
Map<String, String> map2 = Maps.newHashMap();
map2.put("22","22");
list.add(map1);
list.add(map2);
String s = gson.toJson(list);
System.out.println(jsonParser.parse(s).getAsJsonArray());
String s1 = gson.toJson(map1);
System.out.println(jsonParser.parse(s1).getAsJsonObject());
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
String s2 = gson.toJson(map, type); // 通过reflect告知Gson Map键值对的类型
System.out.println(jsonParser.parse(s2).getAsJsonObject());
String s3 = gson.toJson(map); //为null
System.out.println("s3 = " + s3);
System.out.println(jsonParser.parse(s3).getAsJsonObject());
}
}
result:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object: null
at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:84)
at Test3.main(Test3.java:42)
[{"11":"11"},{"22":"22"}]
{"11":"11"}
{"11":"11","111":"22"}
s3 = null
对于ImmutableMap却可以转换json格式
Map<String, String> of = ImmutableMap.of("11", "22");
String s4 = gson.toJson(of);
JsonObject asJsonObject = jsonParser.parse(s4).getAsJsonObject();
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/189521.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有