【问题标题】:Is there a way to convert a JS array in JSON or array in Android?有没有办法在 JSON 中转换 JS 数组或在 Android 中转换数组?
【发布时间】:2019-12-16 15:15:25
【问题描述】:

我有一个从网站源页面获取数据的 Android 应用程序,特别是 JavaScript 对象数组。我想把它转换成我可以在 Android 中管理的东西。有没有办法做到这一点?

我尝试使用 WebView(用户不会看到)来使用 evaluateJavascript 方法,但没有成功。

结果,我会得到这个对象的数组,所以我可以用 Java 管理它们。

编辑:

这是我要转换的字符串示例:

var 对象 = [

                {
        id: "1823746",
        type: "dog",
    },
    {
        id: "2346123",
        type: "cat",
    }

]

【问题讨论】:

    标签: javascript java android json


    【解决方案1】:

    gson 库帮助你。

    new Gson().fromJson("[...]", MyArrayListOfMyObject.class)
    
    class MyArrayListOfMyObject extends ArrayList<MyObject> {}
    
    class MyObject {String id; String type;}
    

    【讨论】:

    • 我收到此错误:com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 31828 path $[60].Something i> 是不是因为我没有在每个字段中都有双引号,正确
    • MyArrayListOfMyObject 数组 = new Gson().fromJson("[{id: \"1823746\",type: \"dog\"},{id: \"2346123\",type: \ "cat\"}]", MyArrayListOfMyObject.class); Log.d("数组:", array.get(0).id);
    • 你的json数组中有两个不合适的逗号
    • [ {id: "1823746", type: "dog"},{id: "2346123",type: "cat",}]
    • 非常感谢您的帮助,我不得不做更多的事情(Es: id -> "id")但 Gson 库成功了!
    【解决方案2】:

    org.json 库会将 JSON 字符串转换为对象数组。

    【讨论】:

    • 问题是该字符串包含一个JavaScript数组..如何将其转换为JSON?
    • 你能添加一个你想转换的字符串的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2020-08-03
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2014-03-20
    • 2015-08-01
    相关资源
    最近更新 更多