如何打印空字符串数组

时间:2018-01-31 01:46:52

标签: java json string arraylist

我正在尝试从.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); 

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分: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];
}