我在生成之后得到了一个错过的字段(添加到我的JsonArray)。 我通过ObjectInputStream接收下面的Json String。
[{"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"}]}]
生成后我收到了所需的字符串,但没有&#34; firstName&#34;元素... 为什么以及如何解决这个问题?感谢
员工类:
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;
}
答案 0 :(得分:0)
不是直接使用员工类,而是可以尝试这样的事情:
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。 如果有效,请告诉我。