目前,我正在开发一个带有WebView前端的原生Android应用程序.

I have something like:

public class dataObject
{
  int a;
  String b;
}

在活动中,

I have made an array of dataObject, say dataObject x[5];

Now i want to pass these 5 dataObject to my javascript webView interface as JSON in a callback function.

我在网上浏览了一下,似乎大多数教程都在讨论如何转换fromJson().关于toJson()的内容不多.我找到了一个让我明白dataObject.toJson()是可行的.

But how can I pass all 5 dataObjects?

推荐答案

Here's a comprehensive example on how to use Gson with a list of objects. This should demonstrate exactly how to convert to/from Json, how to reference lists, etc.

Test.java:

import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


public class Test {

  public static void main (String[] args) {

    // Initialize a list of type DataObject
    List<DataObject> objList = new ArrayList<DataObject>();
    objList.add(new DataObject(0, "zero"));
    objList.add(new DataObject(1, "one"));
    objList.add(new DataObject(2, "two"));

    // Convert the object to a JSON string
    String json = new Gson().toJson(objList);
    System.out.println(json);

    // Now convert the JSON string back to your java object
    Type type = new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> inpList = new Gson().fromJson(json, type);
    for (int i=0;i<inpList.size();i++) {
      DataObject x = inpList.get(i);
      System.out.println(x);
    }

  }


  private static class DataObject {
    private int a;
    private String b;

    public DataObject(int a, String b) {
      this.a = a;
      this.b = b;
    }

    public String toString() {
      return "a = " +a+ ", b = " +b;
    }
  }

}

To compile it:

javac -cp "gson-2.1.jar:." Test.java

And finally to run it:

java -cp "gson-2.1.jar:." Test

Note that if you're using Windows, you'll have to switch : with ; in the previous two commands.

After you run it, you should see the following output:

[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}]
a = 0, b = zero
a = 1, b = one
a = 2, b = two

Keep in mind that this is only a command line program to demonstrate how it works, but the same principles apply within the Android environment (referencing jar libs, etc.)

Json相关问答推荐

如何抓住引号之间的第二次出现?

PowerShell脚本-替换json数组(转义$var将被视为不带双引号的文本)

PowerShell:将Invoke-WebRequest与变量一起使用

将JSON数组组织到菜单中

NoneType 对象的 Python 类型错误

go 语言中的 JSON 到 XML

Bicep脚本中如何设置弹性池的维护窗口?

如何在jolt中使用shift和modify-overwrite-beta

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

从 json 数组中仅提取一个值导致 vb6

如何在 Node.js 中解析包含NaN的 JSON 字符串

如何为所有 API 端点全局设置 http.ResponseWriter Content-Type 标头?

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

JSON RPC - 什么是id?

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

如何在 Perl 中将简单的哈希转换为 json?

错误未判断调用put(K, V)作为原始类型java.util.HashMap的成员

Jackson:忽略 Json 配置值

JSON JQ 如果没有 else