【问题标题】:How to convert JSONObject directly to byteArray without intermediate toString?如何在没有中间 toString 的情况下将 JSONObject 直接转换为 byteArray?
【发布时间】:2019-07-23 08:37:58
【问题描述】:

我有一个从库返回的 JSONObject。有时 JSONObject 太大,在应用 getBytes 将其转换为 byteArray 之前将 toString 应用于 JSONObject 时会导致异常。如何直接将 JSONObject 转换为 ByteArray?

【问题讨论】:

  • 看看this的答案。
  • @AndriiOmelchenko 请推荐一个与 Android 中的 javax.json 兼容的库。上面的示例在 Java 中运行。但对于 android,相同的库不可用。
  • stackoverflow.com/a/35257532/11514311 看这个链接。我认为它会帮助你

标签: android arrays json


【解决方案1】:

试试这个代码

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
Json.createWriter(byteArray).write(jsonObject);
byte[] data = stream.toByteArray()

【讨论】:

【解决方案2】:

示例:

JSONObject obj = new JSONObject();
    obj.put("name", "foo");
    obj.put("num", new Integer(100));
    obj.put("balance", new Double(1000.21));
    obj.put("is_vip", new Boolean(true));
    obj.put("nickname",null);

您的解决方案:

obj.toString().getBytes(theCharset);

【讨论】:

  • toString 方法对我来说是异常。 JSONObject 有时太大了。
猜你喜欢
  • 2021-04-12
  • 2020-03-16
  • 1970-01-01
  • 2018-06-27
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多