繁体   English   中英

如何将 ArrayList 转换为 JSON 不起作用

[英]How to convert an ArrayList to JSON not working

我正在尝试将ArrayList<String>转换为 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);

这是输出:

[{"title":"fes","lat":"27","lng":"876fghfgh85","description":"none"},{"title":"fes","lat":"27","lng":"876fghfgh85","description":"none"},{"title":"fes","lat":"27","lng":"876fghfgh85","description":"none"}]

这不是我想要的! 我错过了什么吗?

您的循环中有一个错误 - 您每次都在重新使用jsonV

尝试将jsonV声明移动到您的循环中:

//copying to another list to a valid format of json
for(int i = 0 ; i<locs.size();i++)
{
    JsonValid jsonV = new JsonValid();
    // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM