如何通过Moshi将对象序列化为Map

时间:2017-11-02 02:17:23

标签: moshi

我想通过Moshi将一个Object序列化为Map.Here是Gson的代码

    public static Map<String, String> toMap(Object obj, Gson gson) {
    if (gson == null) {
        gson = new Gson();
    }
    String json = gson.toJson(obj);
    Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());
    return map;
}

如何用Moshi写作?

4 个答案:

答案 0 :(得分:4)

这是一种方式。查看toJsonValue doc here.

Moshi moshi = new Moshi.Builder().build();

JsonAdapter<Object> adapter = moshi.adapter(Object.class);

Object jsonStructure = adapter.toJsonValue(obj);
Map<String, Object> jsonObject = (Map<String, Object>) jsonStructure;

如果您知道obj的类型,那么最好查找该类型的适配器,而不是Object。 (对象JsonAdadpter必须在每次toJson调用时查找运行时类型。

答案 1 :(得分:1)

class HashMapJsonAdapter<K, V>(
  private val keyAdapter: JsonAdapter<K>,
  private val valueAdapter: JsonAdapter<V>
) : JsonAdapter<HashMap<K, V>>() {

  @Throws(IOException::class)
  override fun toJson(writer: JsonWriter, map: HashMap<K, V>?) {
    writer.beginObject()
    for ((key, value) in map ?: emptyMap<K, V>()) {
      if (key == null) {
        throw JsonDataException("Map key is null at ${writer.path}")
      }
    keyAdapter.toJson(writer, key)
    valueAdapter.toJson(writer, value)
    }
    writer.endObject()
  }

  @Throws(IOException::class)
  override fun fromJson(reader: JsonReader): HashMap<K, V>? {
    val result = linkedMapOf<K, V>()
    reader.beginObject()
    while (reader.hasNext()) {
      val name = keyAdapter.fromJson(reader)
      val value = valueAdapter.fromJson(reader)
      val replaced = result.put(name!!, value!!)
      if (replaced != null) {
        throw JsonDataException("Map key '$name' has multiple values at path ${reader.path} : $replaced and value")
      }
    }
    reader.endObject()
    return result
  }

  override fun toString(): String = "JsonAdapter($keyAdapter=$valueAdapter)"

  companion object
}

答案 2 :(得分:0)

if(document.getElementById('demo').innerHTML=='test'){
   alert('lowercase');
}
if(document.getElementById('demo').innerHTML=='TEST'){
   alert('UPPERCASE');
}

答案 3 :(得分:0)

@ NanoJava8解决方案崩溃,但可以使用Map而不是HashMap

进行较小的更改
Type type = Types.newParameterizedType(Map.class, String.class, Object.class);

JsonAdapter<Map<String,String>> adapter = moshi.adapter(type);

Map<String,String> map = adapter.fromJson(json);

Jesse在答案Moshi支持字段中所述,Map而不是HashMap