2

I'm trying to convert JSON String to List of Object(ResolveInfo) using the below method,

    private List<ResolveInfo> jsonStringToListOfResolveInfo(String response) {
          
            List<ResolveInfo> list = null;
            try {
       
                Gson gson = new GsonBuilder().create();
                Type listOfMyClassObject = new TypeToken<ArrayList<ResolveInfo>>() {}.getType();
                list = gson.fromJson(response, listOfMyClassObject);
    
                if (list!=null){
                    Log.d(TAG, "ResolveInfoList: size - "+list.size());
                }else{
                    Log.d(TAG, "ResolveInfoList: list = gson.fromJson(response, listOfMyClassObject); is null");
                }
    
            } catch (JsonSyntaxException e) {
                Log.i(TAG, "JsonSyntaxException in " + e.getMessage());
            }catch (Exception e){
                Log.d(TAG, "exception is : "+e.getMessage());
            }

          return list;
    }

But, I'm getting the exception like below

Unable to create instance of interface java.lang.CharSequence. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.

What is the reason for this exception ?, Thank you!

FGH
  • 2,900
  • 6
  • 26
  • 59
  • 1
    Does this answer your question? [Deserialize a class containing java.lang.CharSequence member variable](https://stackoverflow.com/questions/58460861/deserialize-a-class-containing-java-lang-charsequence-member-variable) – Marcono1234 Jun 12 '22 at 20:41
  • 1
    Also, when you don't specify a custom type adapter and Gson has no built-in type adapter it uses reflection. Please do not rely on this for third-party classes (in this case Android's `ResolveInfo`). While Gson (unfortunately) does not prevent you from doing this, it makes your code unreliable because you depend on the internal fields of these classes. These implementation details could change between versions, and in this case could even differ between Android versions or devices. Please either write a custom adapter for `ResolveInfo`, or write a custom data class which stores the data. – Marcono1234 Jun 12 '22 at 20:46
  • @Marcono1234 It's working well, could you please answer this question using your previous answer(https://stackoverflow.com/a/72595727/5359340) I don't like to close this question because of the different exception, in the future, it will be helpful to someone who is facing this issue, – FGH Jun 16 '22 at 04:05
  • 1
    Even though the exception message was changed in newer Gson versions I still think that other question already covers this. – Marcono1234 Jun 16 '22 at 21:00

0 Answers0