toJSON() - saving mSuspect?


#1

Is this right?

Book:

if (mPhoto != null) json.put(JSON_PHOTO, mPhoto.toJSON()); json.put(JSON_SUSPECT, mSuspect); return json;

Should be?

if (mPhoto != null) { json.put(JSON_PHOTO, mPhoto.toJSON()); } if (mSuspect != null) { json.put(JSON_SUSPECT, mSuspect); }


#2

We’ve got that in the errata. That’s an error in indentation. We intended to print this:

if (mPhoto != null)
     json.put(JSON_PHOTO, mPhoto.toJSON());
json.put(JSON_SUSPECT, mSuspect);
return json;

Next time, we’ll include the braces. :slight_smile:

No null check is required on mSuspect.


#3

I get an exception in CrimeLab when the app is starting up, loading the crimes, and one of them does not have a title. Why does it bomb when the title is null but not when mSuspect is null?

Thanks.

EDIT: OK, it is because of this method in Crime.java. Add the check for JSON_TITLE works. So, JSON does not save anything if the field is null.

public Crime(JSONObject json) throws JSONException { mId = UUID.fromString(json.getString(JSON_ID)); if (json.has(JSON_TITLE)) { mTitle = json.getString(JSON_TITLE); }


#4

Yep, you got it.

I’ll add a remark to the errata.