Gson deserialization of List into realmList

前端 未结 4 613
刺人心
刺人心 2020-12-01 05:18

I\'m using retrofit with gson to deserialize my json into realm objects. This works very well for the most part. Trouble arises when dealing with

Rea

4条回答
  •  感动是毒
    2020-12-01 06:01

    The error message "Expected a string but was NAME" can be solved by retrieving the name of the json object in the JsonReader before the actual json object (which is a String in your case).

    You can take a look at the Android documentation for JsonReader. It has detailed explanation and code snippet. You can also take a look at the readMessage method in the sample code snippet in the documentation.

    I have modified your read method to what I think it should be. NOTE: I didn't test the code, so there may be some minor errors in it.

    @Override
    public RealmPerson read(JsonReader in) throws IOException {
        RealmPerson rList = new RealmPerson();
        in.beginObject();
        String name = "";
        while (in.hasNext()) {
            name = in.nextName();
    
            if (name.equals("userId")) {
                String userId = in.nextString();
                // update rList here 
            } else if (name.equals("otherStuff")) {
                // since otherStuff is a RealmList of RealmStrings,
                // your json data would be an array
                // You would need to loop through the array to retrieve 
                // the json objects
                in.beginArray();
                while (in.hasNext()) {
                    // begin each object in the array
                    in.beginObject();
                    name = in.nextName();
                    // the RealmString object has just one property called "value"
                    // (according to the code snippet in your question)
                    if (name.equals("val")) {
                        String val = in.nextString();
                         // update rList here 
                    } else {
                        in.skipValue();
                    }
                    in.endObject();
                }
                in.endArray();
            } else {
                in.skipValue();
            }
        }
        in.endObject();
    
    
        return rList;
    }
    

    Let me know if this helps.

提交回复
热议问题