Gson解析数据为null的错误

数据

{"someFieldName":"xyz"}


public class ExampleBean{
    public String someFieldName;
}

错误解析

    public static Gson getGson() {
        return new GsonBuilder().setFieldNamingPolicy(
        FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    }

    public static  T json2Bean(String result , Class clazz){
        Gson gson = getGson();
        T t = gson.fromJson(result, clazz);
        return t;
    }

//解析代码
ExampleBean bean=GsonUtil.json2Bean(response.data, ExampleBean.class);
这里response.data是{"someFieldName":"xyz"}

//解析结果为bean=null;

分析

查询没有报错,但是解出来为null,也不知道怎么调试。于是我就追查源码。结果发现问题出在FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES。

  /**
   * Using this naming policy with Gson will modify the Java Field name from its camel cased
   * form to a lower case field name where each word is separated by an underscore (_).
   *
   * 

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

*
    *
  • someFieldName ---> some_field_name
  • *
  • _someFieldName ---> _some_field_name
  • *
  • aStringField ---> a_string_field
  • *
  • aURL ---> a_u_r_l
  • *
*/ LOWER_CASE_WITH_UNDERSCORES() { @Override public String translateName(Field f) { return separateCamelCase(f.getName(), "_").toLowerCase(Locale.ENGLISH); } }

原来FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES会将”驼峰样式的参数someFieldName”解析为some_field_name。

解决方案

方案1、变量名字全部用小写。(服务器和客户端同时约定好为小写somefieldname)
方案2、客户端解析不采用FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES。

Gson gson = new Gson();
ExampleBean bean=gson.fromJson(response.result, NewFlashDetailEntity.class);

你可能感兴趣的:(gson,Android)