在GSON解析JSON的初始资本主要问题 [英] JSON Initial capital key issue with parsing in GSON

查看:201
本文介绍了在GSON解析JSON的初始资本主要问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有previously在REST API像下面JSON响应,

I have previously JSON response in REST API like below,

例如:

{ID:1234}

{"id":"1234"}.

我创建了一个POJO类来设置如下图所示。

I created an POJO class to set it like below.

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

    @SerializedName("id")
    @Expose
    private String id;

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }
}

和我与GSON解析如下图所示。

And I am parsing with GSON like below

Example response = new Gson().fromJson(jsonResponse, Example .class);

现在,响应更改为

{ID:1234}

{"Id":"1234"}

和我的整个解析将返回我空因首字母大写。

And my whole parsing is returning me null due to initial capital letter.

我试过很多事情要解决它,但我不能得到任何的解决方案。我有一个像

I tried many things to solve it out but I can't get any solution for it. I have only suggestions like


  • 您应该初始资本变更@SerializedName的名称(但我有成千上万的对象)

是否有GSON不会依赖于资本或关键的小写任何解决方案?

Is there any solution that GSON won't depend upon capitalization or lower case of key?

推荐答案

我认为你可以使用<一个href=\"http://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/FieldNamingPolicy.html\"相对=nofollow> FieldNamingPolicy在GSON构建器是这样的:

I think you can use FieldNamingPolicy in your Gson Builder like this :

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

我觉得你的情况,你将需要使用基于您要使用的分离器LOWER_CASE_WITH_UNDERSCORES或LOWER_CASE_WITH_DASHES。

I think in your case you will need to use LOWER_CASE_WITH_UNDERSCORES or LOWER_CASE_WITH_DASHES based which separator you want to use.

<一个href=\"http://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/FieldNamingPolicy.html\"相对=nofollow>从文档如果你设置该标志将骆驼套管形式转换为小写的字段名。

From the docs if you set this flag it will convert camel cased form to a lower case field name.

编辑:结果
该SerializedName注解将覆盖任何字段命名策略,所以你必须要小心它 - > <一个href=\"http://google-gson.google$c$c.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html\"相对=nofollow>来源

这篇关于在GSON解析JSON的初始资本主要问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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