问题
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