Moshi vs Gson在Android中 [英] Moshi vs Gson in android

查看:754
本文介绍了Moshi vs Gson在Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在决定是否使用 Moshi by square 或Gson来序列化和反序列化模型数据.

I'm deciding on whether to use Moshi by square or Gson to serialize and deserialize model data.

我一直不喜欢Gson的一件事是我认为它使用的反射在Android上可能很慢?莫希也使用反射吗?

one thing i always did not like about Gson is i think it uses reflection which can be slow on android? Does Moshi use reflection also?

moshi vs Gson有哪些优缺点?

What are some of the pros and cons of moshi vs Gson?

我认为它们相似.例如,以创建typeAdapter:

I see them as similar. take for example this statement that creates a typeAdapter:

class CardAdapter {
  @ToJson String toJson(Card card) {
    return card.rank + card.suit.name().substring(0, 1);
  }

  @FromJson Card fromJson(String card) {
    if (card.length() != 2) throw new JsonDataException("Unknown card: " + card);

    char rank = card.charAt(0);
    switch (card.charAt(1)) {
      case 'C': return new Card(rank, Suit.CLUBS);
      case 'D': return new Card(rank, Suit.DIAMONDS);
      case 'H': return new Card(rank, Suit.HEARTS);
      case 'S': return new Card(rank, Suit.SPADES);
      default: throw new JsonDataException("unknown suit: " + card);
    }
  }
}

并使用它就像在gson中一样注册它:

and to use it register it just like in gson:

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

我猜它的好处是在typeAdapter中使用了注释.我正在寻找是否可以切换到Moshi来获得任何性能提升.

I guess the advantages would be the annotation being used in the typeAdapter. I'm looking to find out if there are any performance gains if I switch to Moshi.

推荐答案

Moshi使用Okio优化了Gson所不具备的一些功能.

Moshi uses Okio to optimize a few things that Gson doesn’t.

  • 读取字段名称,Moshi不必分配字符串或进行哈希查找.
  • Moshi将输入作为UTF-8字节序列扫描,然后懒惰地转换为Java字符.例如,它不需要将整数文字转换为char.
  • When reading field names, Moshi doesn’t have to allocate strings or do hash lookups.
  • Moshi scans the input as a sequence of UTF-8 bytes, converting to Java chars lazily. For example, it never needs to convert integer literals to chars.

如果您已经在使用Okio流,则这些优化的优势尤其明显. Retrofit

The benefits of these optimizations are particularly pronounced if you’re already using Okio streams. Users of Retrofit and OkHttp in particular benefit from Moshi.

关于Moshi起源的进一步讨论在我的帖子中, Moshi,另一个JSON处理程序.

Further discussion on the origins of Moshi are in my post, Mos another JSON Processor.

这篇关于Moshi vs Gson在Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆