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 except json. I have only access to java controller this need to be done pure java..
我是Vector和Json的新手。我想使用java将Vector转换为Json ..我有像[[001555,LK,24,KO],[0005,125,SL,85,FOO]的Vector Sout打印]我的前端只有json。我只能访问java控制器,这需要做纯java ..
ex:- response need to like this.. { "id": 1, "string1": "001555", "string2": "LK", "string3": "24", "string4": "KO" }, { "id": 0005, "string1": "125", "string2": "SL", "string3": "85", "string4": "FOO" },
例如: - 响应需要像这样.. {“id”:1,“string1”:“001555”,“string2”:“LK”,“string3”:“24”,“string4”:“KO”}, {“id”:0005,“string1”:“125”,“string2”:“SL”,“string3”:“85”,“string4”:“FOO”},
1 个解决方案
#1
0
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"}]
#1
0
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"}]