0

我正在尝试使用org.json中的toString()方法对典型的 Java 对象进行字符串化。但是,我的 bean 中的 Collections 或 Array 类型成员以字节数组的形式进行了字符串化。我已经列出了一个示例代码来说明这个问题。

这是我所期望的:

{
   "nonWorkingDays":[
      "Saturday",
      "Sunday"
   ],
   "workingDays":[
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday"
   ],
   "days":[
      1,
      2,
      3,
      4,
      5,
      6,
      7
   ]
}

这就是我得到的:

{
  "nonWorkingDays": [
    {
      "bytes": [
        {},
        {}, ...
      ],
      "empty": false
    },
    {
      "bytes": [
        {},
        {}, ...
      ],
      "empty": false
    }
  ],
  "workingDays": [
    {
      "bytes": [
        {},
        {}, ...
      ],
      "empty": false
    },
    {
      "bytes": [
        {},
        {}, ...
      ],
      "empty": false
    }, ...
  ],
  "days": [
    {},
    {}, ...
  ]
}

最后,这是我的代码:

/* Week.java */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Week {
    private List<String> workingDays = new ArrayList<String>();
    private String[] nonWorkingDays;
    int days[];

    public Week() {
        String[] workingDaysArray = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
        workingDays.addAll(Arrays.asList(workingDaysArray));
        nonWorkingDays = new String[] { "Saturday", "Sunday" };
        days = new int[] { 1, 2, 3, 4, 5, 6, 7 };
    }

    public List<String> getWorkingDays() {
        return workingDays;
    }

    public String[] getNonWorkingDays() {
        return nonWorkingDays;
    }

    public int[] getDays() {
        return days;
    }

    @Override
    public String toString() {
        return "Week [workingDays=" + workingDays + ", nonWorkingDays=" + Arrays.toString(nonWorkingDays) + ", days="
                + Arrays.toString(days) + "]";
    }
}

/* WeekTest.java */

import org.json.JSONException;
import org.json.JSONObject;

public class WeekTest {
    public static void main(String[] args) throws JSONException {
        Week myWeek = new Week();
        JSONObject myWeekJSON = new JSONObject(myWeek);
        String myWeekJSONString = myWeekJSON.toString(2);
        System.out.println(myWeekJSONString); // Formatted JSON string
        System.out.println(myWeek); // Output from Week's toString()
    }
}

顺便说一句,Week 的 toString() 方法输出如下:

Week [workingDays=[Monday, Tuesday, Wednesday, Thursday, Friday], nonWorkingDays=[Saturday, Sunday], days=[1, 2, 3, 4, 5, 6, 7]]

编辑:

问题似乎出在这个 maven artifact上。从这个 github repo更新到源代码后,我得到了一切修复。请看下面的评论。

4

0 回答 0