Parse realm model using jackson

点点圈 提交于 2020-01-14 10:22:51

问题


Getting unknown key while converting realm model into json object using jackson library.

Here is my realm model instance.

    public class RecordData extends RealmObject {

    public RecordData() {

    }

    private FormData formData;

    @Nullable
    @JsonProperty("values")
    private RealmList<Values> values;

    @Nullable
    @JsonProperty("value")
    private String value;
}

Code for converting realm model to json object.

JSONObject recordDataJsonObject = new JSONObject(new ObjectMapper().writeValueAsString(formData.getRecordData()));

Output from parse json :

{"loaded":true,"managed":false,"valid":true,"value":"fdfdf","values":[]}

Realm version : io.realm:realm-gradle-plugin:4.1.1

Rxjava version : 'io.reactivex.rxjava2:rxjava:2.1.6'

Jackson version : com.fasterxml.jackson.core:jackson-databind:2.8.6

Why i am getting loaded, managed and valid boolean values ?


回答1:


Write response from ObjectMapper, you have to do this:

public static String getJsonFromObject() {
        ObjectMapper objectMapper = ObjectMapperHelper.getObjectMapperInstance();
        String jsonString = null;
           try {
            jsonString = objectMapper.writeValueAsString(formData.getRecordData());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString != null ? jsonString : "";
    }

and get your response in JsonObject :

try {
    JSONObject jsonObject = new JSONObject().getJSONObject(getJsonFromObject());
     } catch (JSONException e) {
       e.printStackTrace();
       }

Happy coding!!




回答2:


I have solved it using Gson parsing library.

JSONObject recordDataJsonObject = new JSONObject(new Gson().toJson(formData.getRecordData()));

Its not return unknown key. Output is here.

{"value":"fdfdf","values":[]}

Hope you will find this solution if you are facing same case.




回答3:


You could use @JsonIgnoreProperties annotation:

@JsonIgnoreProperties({"loaded", "managed", "valid"})
public class RecordData extends RealmObject {

    public RecordData() {

    }

    private FormData formData;

    @Nullable
    @JsonProperty("values")
    private RealmList<Values> values;

    @Nullable
    @JsonProperty("value")
    private String value;
}

Another option is to use @RealmClass public class RecordData implements RealmModel.



来源:https://stackoverflow.com/questions/47177201/parse-realm-model-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!