【问题标题】:How to print empty String Array如何打印空字符串数组
【发布时间】:2018-07-10 00:51:21
【问题描述】:

我正在尝试从 .dat 文件中读取数据,然后将它们写入 .json。问题是有些人在文件中没有电子邮件。所以,我想要类似的东西

“电子邮件”:[]

 {
    "personCode": "2342",
    "firstName": "Jeff",
    "lastName": "Spalding",
    "address": {
      "street": "123 Friendly Street",
      "city": "Ottawa",
      "state": "ON",
      "zip": "K1A 0G9",
      "country": "Canada"
    },
    "emails": []
  },

但是,我的代码没有打印任何电子邮件[]

{
  "personCode": "2342",
  "firstName": "Jeff",
  "lastName": "Spalding",
  "address": {
    "street": "123 Friendly Street",
    "city": "Ottawa",
    "state": "ON",
    "zip": "K1A 0G9",
    "country": "Canada"
  }
}

我的代码:

String[] email = null;
    String[] emailTokens = data[3].split(",");
        for (int i = 0; i < emailTokens.length; i++) {
             email = emailTokens;
        }

Person person = new Person(personCode, firstName, lastName, address, email);
    personList.add(person); 

有什么想法吗?谢谢!

【问题讨论】:

  • 为什么您认为需要空的emails 字段?您不能只检查相应 Java JSON 对象中该字段是否为空吗?

标签: java json string arraylist


【解决方案1】:

你的循环没有意义:

for (int i = 0; i < emailTokens.length; i++) {
    email = emailTokens;  // Here you assign the some emailTokens N times.
}

可以简化为:

String[] email = data[3].split(",");

关于您在 JSON 中遗漏电子邮件的问题,请尝试传递空数组:

String[] email = data[3].split(",");
if (email == null) {
    email = new String[0];
}

【讨论】:

  • 谢谢。我通过使用 ArrayList emailList = new ArrayList(); 找到了另一种方法if (data.length == 4).
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多