Home > other >  How to leave json object as raw string in Moshi
How to leave json object as raw string in Moshi

Time:09-12

I want be able to save json object as raw json String. I've already have solution wit JSONObject, but it seems a bit redundant. Is there any way to get json string from reader?

class ObjectAsStringFactory : JsonAdapter.Factory {
override fun create(
    type: Type,
    annotations: MutableSet<out Annotation>,
    moshi: Moshi
): JsonAdapter<*>? {
    val delegateAnnotations = Types.nextAnnotations(annotations, ObjectAsString::class.java)
        ?: return null
    if (Types.getRawType(type) !== String::class.java) {
        throw IllegalArgumentException("@ObjectAsString requires the type to be String. Found this type: $type")
    }
    val delegateAdapter: JsonAdapter<String?> = moshi.adapter(type, delegateAnnotations)

    return ObjectAsStringAdapter(delegateAdapter)
}

class ObjectAsStringAdapter(private val wrapped: JsonAdapter<String?>) : JsonAdapter<String>() {
    override fun fromJson(reader: JsonReader): String? {
        return (reader.readJsonValue() as? Map<*, *>)?.let { data ->
            try {
                JSONObject(data).toString()
            } catch (e: JSONException) {
                return null
            }
        }
    }

    override fun toJson(writer: JsonWriter, value: String?) {
        wrapped.toJson(writer, value)
    }
}
}

CodePudding user response:

Try JsonReader.nextSource(). You can read the encoded JSON bytes either as a String or as a ByteString.

String encodedJson;
try (BufferedSource bufferedSource = reader.nextSource()) {
  encodedJson = bufferedSource.readUtf8();
}
  • Related