Should the names of the class fields and the names of the types of the class to which I am parsing Json fully correspond to the names of the fields contained in Json? And what else there are moments which can break validity of parsing?

SignInResponse response = gson.fromJson(result, SignInResponse.class); 

After this attempt at parsing, the application just crashes.

  • 2
    Field names may differ, but then you need to use annotations. You better describe the specific problem or error you encountered. So it will be easier to help you. - eugeneek
  • added a question - Clarence
  • one
    I would advise using the org.json library - Peter Samokhin
  • one
    Well, now add the contents of the SignInResponse class SignInResponse value of the result and the structure of the error received. - eugeneek
  • @PeterSamokhin tried using the org.json library - this is the best solution, thanks for directing you to the right path - Clarence

1 answer 1

The default should be the same, but you can change it. The easiest way is to apply a common naming pattern to all fields. If you use Gson, then FieldNamingPolicy is responsible for this. Using FieldNamingPolicy , for example, you can normally deserialize JSON with pascal-case fields into Java objects, whose field names are usually in camel-case. FieldNamingPolicy set up like this:

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

Take a look at the documentation , there certainly is a suitable policy for your case.

If for some reason you have a different naming template in one object or some unpleasant abbreviations, then you can use annotations, which can explicitly set the key for which this field is available in JSON. In Gson, this is the SerializedName annotation (the link is a simple example of use).