首页 > 解决方案 > 创建 JSON 文件时如何使用在 Android Studio 上编写的 JSON 数组?

问题描述

我正在制作一个应用程序,它从用户(姓名、姓氏等)获取数据并将数据保存在 JSON 文件中。我所做的是在从用户那里获取数据后,将它们插入字符串数组并将字符串数组转换为 JSON 数组。这是代码:

public void toJSON(){

  try {
    JSONArray List = new JSONArray();
    for (int j = 0; j < 10; j++) {
      List.put(ad[j]);
      List.put(soyad[j]);
      List.put(sehir[j]);
      System.out.print(List.toString(1));
    }
  } catch (JSONException e) {
    e.printStackTrace();
  }

}

我必须创建一个 JSON 文件,但我不知道如何在用户输入数据后向其中添加数据。

标签: javascriptandroidjson

解决方案


这就是将数据放入 JSONArray 的方式。

    JSONArray array = new JSONArray();
    JSONObject object = new JSONObject();
    try {
        object.put("query", "ran 3 miles");
        object.put("gender", "female");
        object.put("weight_kg", 72.5);
        object.put("height_cm", 167.64);
        object.put("age", 30);
        array.put(object);
    } catch (JSONException e) {
        e.printStackTrace();
    }

这将打印

[{"gender":"female","weight_kg":72.5,"height_cm":167.64,"query":"跑了 3 英里","age":30}]

如果你想使用 Lists<>... 这样做。

    JSONArray array = new JSONArray();
    List<String> list = new ArrayList<>();
    JSONObject object = new JSONObject();
    try {
        object.put("age", 5);
        object.put("name", "bill");
        list.add("string1");
        list.add("string2");
        object.put("strings", list);
        array.put(object);
    } catch (JSONException e) {
        e.printStackTrace();
    }

这将打印以下内容:

[{"strings":["string1","string2"],"name":"bill","age":5}]

以你刚刚学到的东西,让我们更深入。

假设您有一个姓名和电子邮件编辑文本,就像这样。

EditText name = findViewById(R.id.name);
EditText email = findViewById(R.id.email);

你有一个 onclick 监听器,也许是一个“保存”按钮。当您录制它时,您需要从那些编辑文本中获取信息。

... // clicked save
String nameString = name.getText().toString().trim();
String emailString = email.getText().toString().trim();
// Create your json file.

    JSONArray array = new JSONArray();
    JSONObject object = new JSONObject();
    String nameString = "john"; // dont need this, this is from the edit text (example)
    String emailString = "email@email.com"; // dont need this, this is from the edit text (example)
    try {
        object.put("name", nameString);
        object.put("email", emailString);
        array.put(object);
        System.out.println(array);
    } catch (JSONException e) {
        e.printStackTrace();
    }

这将打印出来...

[{"name":"john","email":"email@email.com"}]

将字符串列表转换为 JSONArray:

辅助方法:

public static JSONArray convertToJSON (List<String> list) {
    JSONArray array = new JSONArray();
    array.put(list);
    return array;
}

代码:

List<String> list = new ArrayList<>();

    list.add("string1");
    list.add("string2");
    list.add("string3");
    list.add("string4");
    list.add("string5");
    list.add("string6");
    list.add("string7");
    list.add("string8");

    System.out.println(convertToJSON(list));

结果

[["string1","string2","string3","string4","string5","string6","string7","string8"]]


推荐阅读