Skip to content

JSON deserialization ignores case of setters #1830

@cushon

Description

@cushon

The following example shows that json deserialization ignores the case of the setters, and deserializes two different fields that differ only in case to the same setter.

I stepped through in a debugger, and I think the issue is this logic that setups up a FieldInfo for deserialization ignores case:

if (Ascii.toLowerCase(method.getName()).equals("set" + Ascii.toLowerCase(field.getName()))
&& method.getParameterTypes().length == 1) {

That logic was added as part of ff93479


Repro

With com.google.http-client:google-http-client-gson:1.28.0

Serialized: {"passCode":"pass1","passcode":"pass2"}
{"passCode":"pass2"}

With com.google.http-client:google-http-client-gson:1.27.0

Serialized: {"passCode":"pass1","passcode":"pass2"}
{"passCode":"pass1","passcode":"pass2"}
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.Key;

import java.io.StringReader;
import java.io.StringWriter;

public class Repro {

  public static final class Data extends GenericJson {
    @Key String passcode;
    @Key String passCode;

    public String getPasscode() {
      return passcode;
    }

    public Data setPasscode(String passcode) {
      this.passcode = passcode;
      return this;
    }

    public String getPassCode() {
      return passCode;
    }

    public Data setPassCode(String passCode) {
      this.passCode = passCode;
      return this;
    }
  }

  public static void main(String[] args) throws Exception {
    String serialized;
    {
      Data c = new Data().setPassCode("pass1").setPasscode("pass2");
      StringWriter writer = new StringWriter();
      new GsonFactory().createJsonGenerator(writer).serialize(c);
      serialized = writer.toString();
    }
    System.out.println("Serialized: " + serialized);

    Data parsedData =
        new GsonFactory()
            .createJsonObjectParser()
            .parseAndClose(new StringReader(serialized), Data.class);

    System.out.println(parsedData);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions