Search code examples
javajsonvector

Vector Convert to Json Using Java


I am new to Vector and Json. I want to convert Vector to Json using java.. I have Vector Sout print like [[1, 001555, LK, 24, KO], [0005, 125, SL, 85, FOO]] My front end only accepts JSON. I have only access to Java controller, so this needs to be done in pure Java.

ex:- response needs to be like this:

{ "id": 1, "string1": "001555", "string2": "LK", "string3": "24", "string4": "KO" },
{ "id": 0005, "string1": "125", "string2": "SL", "string3": "85", "string4": "FOO" },

Solution

  • You can try something like this :-

    import java.util.Vector;
    import org.json.JSONObject;
    import org.json.JSONArray;
    import org.json.JSONException;
    
    public static void main(String[] args) {
    
        Vector<Vector> v = new Vector();
    
        Vector v1 = new Vector(); 
        v1.add("1"); 
        v1.add("001555"); 
        v1.add("LK"); 
        v1.add(24); 
        v1.add("KO"); 
    
        Vector v2 = new Vector(); 
        v2.add("0005"); 
        v2.add("125"); 
        v2.add("SL"); 
        v2.add("85"); 
        v2.add("FOO"); 
    
        v.add(v1);
        v.add(v2);
    
        JSONArray ja = new JSONArray();
    
        Vector tmp;
    
        for(int j=0; j<v.size(); j++)
        {
            tmp = v.get(j);
    
            JSONObject obj = new JSONObject();
            for (int i=0; i<tmp.size(); i++)
            {
                try {
                    if(i==0)
                        obj.put("id", tmp.get(i));
                    else
                        obj.put("String"+i, tmp.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            ja.put(obj);
        }   
    
        System.out.println(ja.toString());
    
    }
    

    Output is :-

    [{"id":"1","String4":"KO","String3":24,"String2":"LK","String1":"001555"},{"id":"0005","String4":"FOO","String3":"85","String2":"SL","String1":"125"}]