如何使用GSON将JSON值映射到不同的类 [英] How to map JSON values onto a different class with GSON

查看:185
本文介绍了如何使用GSON将JSON值映射到不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在C#中有一个类,这个类在C#中有一个类, :

  class Test 
{
public string Foo {get;组;当我使用System.Web.Script.Serialization.JavaScriptSerializer对该类进行序列化时}}
}

,我得到:

  {Foo:Bar} 

在java中我有一个类:

  class Test 
{
private String foo;
public String getFoo(){
return foo;
}

public void setFoo(String foo){
this.foo = foo;



$ b我试图用GSON来解析JSON:

  Gson gson = new Gson(); 
Test test = gson.fromJson(getJson(),Test.class);

但我得到空值。

如何将JSON值映射到稍微不同的类,以便我仍然可以在每种语言中使用最佳实践命名约定。 Gson默认使用字段名称,因此您的字段需要命名为 UpTime ComputerName 等等从Java命名的角度来看,这将是亵渎神明的。



保持字段正确地以Java风格命名为较低的骆驼大小写,并告诉Gson使用 FieldNamingPolicy.UPPER_CAMEL_CASE 来代替:

  Gson gson = new GsonBuilder()
.setFieldNamingPolicy FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
统计stats = gson.fromJson(response.getJson(),Statistics.class);

或者,您可以调整C#端以输出较低的骆驼事件 { upTime:...} 当然。


Ok, I figured out my original question which was a trivial naming issue, so I will repurpose this question for the actual problem.

I have a class in C#:

class Test
{
    public string Foo { get; set; }
}

When I serialize the class with System.Web.Script.Serialization.JavaScriptSerializer, I get:

{"Foo":"Bar"}

In java I have a class:

class Test
{
    private String foo;
    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

I'm attempting to use GSON to parse the JSON:

Gson gson = new Gson();
Test test = gson.fromJson(getJson(), Test.class);

But I get null values.

How can I map the JSON values onto a slightly different class so I can still use best practice naming conventions in each language.

解决方案

Gson by default uses the field names as-is, so your fields would need to be named UpTime, ComputerName, etc. From a Java naming perspective that would be blasphemous, though.

Keep your fields properly named in Java style as lower camel case and tell Gson to use FieldNamingPolicy.UPPER_CAMEL_CASE instead:

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
    .create();
Statistics stats = gson.fromJson(response.getJson(), Statistics.class);

Alternatively, you could adapt the C# side to output lower camel case {"upTime" : ... } of course.

这篇关于如何使用GSON将JSON值映射到不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆