Java 如何将ArrayList转换为不工作的JSON
我正在尝试将Java 如何将ArrayList转换为不工作的JSON,java,json,Java,Json,我正在尝试将ArrayList转换为JSON对象。问题是我在任何地方都得到了相同的值 这是我的密码: Location l = new Location((long) 1,"u222","fdfgs","morococ","2dqrg","8drgf5","8dfg"); Location l2 = new Location((long) 1,"u22
ArrayList
转换为JSON对象。问题是我在任何地方都得到了相同的值
这是我的密码:
Location l = new Location((long) 1,"u222","fdfgs","morococ","2dqrg","8drgf5","8dfg");
Location l2 = new Location((long) 1,"u222","fedsfsds","modfrococ","27","876gtfgfg85","8 25 98");
Location l3 = new Location((long) 1,"u222","fes","morococ","27","876fghfgh85","8 25 98");
List<Location> locs = new ArrayList<Location>();;
locs.add(l);
locs.add(l2);
locs.add(l3);
List<JsonValid> jsons = new ArrayList<JsonValid>();
JsonValid jsonV = new JsonValid();
//copying to another list to a valid format of json
for(int i = 0 ; i<locs.size();i++)
{
jsonV.title = locs.get(i).city;
jsonV.lat = locs.get(i).latitude;
jsonV.lng = locs.get(i).longitude;
jsons.add(jsonV);
}
System.out.println(jsons.size());
gson = new Gson();
String jsonStudents = gson.toJson(jsons);
//Here i'm getting the same values
System.out.println(jsonStudents);
这不是我想要的!我遗漏了什么吗?您的循环中有一个bug-您每次都在使用
jsonV
尝试将jsonV
声明移动到循环中:
//copying to another list to a valid format of json
for(int i = 0 ; i<locs.size();i++)
{
JsonValid jsonV = new JsonValid();
// ...
}
//将复制到另一个列表以获得json的有效格式
对于(int i=0;i
//copying to another list to a valid format of json
for(int i = 0 ; i<locs.size();i++)
{
JsonValid jsonV = new JsonValid();
// ...
}