java GSON 可以以不区分大小写的方式反序列化吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13171058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:44:40  来源:igfitidea点击:

Can GSON deserialize in a case-insensitive way

javajsongson

提问by Sam Goldberg

In prototyping communication between .NET desktop app and Java server, using REST with JSON posts, I am running into a case-sensitivity issue. The .NET objects have there properties in Pascal Casing (which is conventional for .NET), e.g.: Symbol, EntryValue(etc), while the Java representation of same object uses camel casing, e.g. symbol, entryValue.

在 .NET 桌面应用程序和 Java 服务器之间的原型通信中,使用带有 JSON 帖子的 REST,我遇到了区分大小写的问题。.NET 对象在 Pascal Casing(这是 .NET 的常规)中有一些属性,例如:( Symbol, EntryValue等),而同一对象的 Java 表示使用驼峰式大小写,例如symbol, entryValue.

The server receives json value as:

服务器接收 json 值如下:

{"EntrySize":100,"Symbol":"AMZN"}

But Gson doesn't deserialize in case-insensitive manner. Is there any way to get Gson to do this?

但是 Gson 不会以不区分大小写的方式反序列化。有没有办法让 Gson 做到这一点?

回答by Jeff Bowman

Use FieldNamingPolicyon a GsonBuilder, to get your Gsonobject. Yours seems to match UPPER_CAMEL_CASE.

FieldNamingPolicyGsonBuilder, 上使用以获取您的Gson对象。你的似乎匹配UPPER_CAMEL_CASE

Gson gson = new GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create();

For any exceptions, annotate your class field with a @SerializedNameannotation.

对于任何例外情况,请使用注释对您的类字段进行@SerializedName注释。