Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add List<String> to the JSONArray

Tags:

java

json

I am trying to greate JSON with the JSON library. At the momant I am creating JSONArray to add to add all the value in my List to it but I am facing this Problem

he method put(int, boolean) in the type JSONArray is not applicable for the arguments (String, List)

at this line arrivalMoFr.put("mon-fri", timeEntries); How can I add List to the JSONArray?

I appreciate any help.

Code:

    List<String> timeEntries = entry.getValue();

    try {
        JSONObject timeTable = new JSONObject();
        timeTable.put("route", route);

        JSONObject info = new JSONObject();
        info.put("direction", direction);

        JSONObject stops = new JSONObject();     
        stops.put("stops_name", key);

        JSONObject arrivals = new JSONObject();
        JSONArray arrivalMoFr  = new JSONArray();
                        //The error is here.
        arrivalMoFr.put("mon-fri", timeEntries);

        arrivals.put("mon-fri", arrivalMoFr);

        stops.put("arrival_time", arrivals);


        info.put("stops", stops);
        timeTable.put("info", info);

        System.out.println(timeTable.toString(3));


    }

Edit: I added it like this but I am getting now this result:

JSONObject arrivals = new JSONObject();
                JSONArray arrivalMoFr  = new JSONArray();
                arrivalMoFr.put( timeEntries);

                arrivals.put("mon-fri", arrivalMoFr);

Result:

{
   "route": "4",
   "info": {
      "stops": {
         "arrival_time": {"mon-fri": [[
            "05:04",
            "18:41",
            "19:11",
            "19:41",
            "20:11"
         ]]},
         "stops_name": "Heiweg "
      },
      "direction": "Groß Grönau"
   }
}
like image 435
MrPencil Avatar asked Nov 07 '25 09:11

MrPencil


2 Answers

JSONArray att = new JSONArray(YourList);
like image 111
Ahmad Sanie Avatar answered Nov 09 '25 02:11

Ahmad Sanie


You can use Gson to convert List<String> to JSON

List<String> listStrings = new ArrayList<String>();
listStrings.add("a");
listStrings.add("b");

Gson objGson = new Gson();
System.out.println(objGson.toJson(listStrings));

Output

["a","b"]
like image 28
Vicky Thakor Avatar answered Nov 09 '25 03:11

Vicky Thakor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!