【问题标题】:Adding to JsonArray results with missing elements添加到缺少元素的 JsonArray 结果
【发布时间】:2015-12-29 17:05:36
【问题描述】:

在生成(添加到我的 JsonArray)后,我得到了一个遗漏的字段。 我通过 ObjectInputStream 接收下面的 Json 字符串。

[{"firstName":"Vasile","lastName":"Petraru","department":"Management","salary":5600},{"firstName":"Ion","lastName":"Andronic","department":"Finante","salary":3222}]

 Gson gson = new Gson();
 String a =  new String(inputStream.readObject().toString());
 JsonParser parser = new JsonParser();
 JsonArray jArray = parser.parse(a).getAsJsonArray();

 ArrayList<Employee> employees = new ArrayList<>();
 for(JsonElement obj : jArray){
      Employee b = gson.fromJson(obj,Employee.class);
      employees.add(b);
 }

像这样添加到 JsonArray 之后:

public String generateJSON() {
    JSONObject object = new JSONObject();
    JSONArray array = new JSONArray();
    try {
        object.put("Employees", employees);
        array.put(object); // <-- here is the probem...
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return array.toString();
}

a = generateJSON();
System.out.println("\nAfter generating: " + a);
// --->

[{"Employees":[{"lastName":"Petraru","salary":5600,"department":"Management"},{"lastName":"Andronic","salary":3222,"department":"Finante"}]}]

生成后,我收到了所需的字符串,但没有“firstName”元素... 为什么以及如何解决这个问题?谢谢

员工类:

public class Employee implements Serializable {
public String firstName;
public String lastName;
public String department;
public int salary;

public Employee(String firstName, String lastName, String department, int salary){
    this.firstName = firstName;
    this.lastName = lastName;
    this.department = department;
    this.salary = salary;
}

【问题讨论】:

  • 当您将对象放入数组时,员工对象是否正确填充?
  • 当然,我已经打印了,一切正常。

标签: java arrays json


【解决方案1】:

您可以尝试这样的方法,而不是直接使用员工类:

JSONObject jo = new JSONObject();
jo.put("firstName", employee.getFirstName);
jo.put("lastName", employee.getLastName);

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

并在 Employee 类中声明 getter 和 setter。 让我知道这是否有效。

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2018-11-05
    • 1970-01-01
    • 2012-01-06
    相关资源
    最近更新 更多