我正在尝试下面的代码....
public String listToJsonString(String keyName, List<StyleAttribute> attrs) {
JSONObject json = new JSONObject();
json.accumulate(keyName, attrs);
return json.toString();
}
Run Code Online (Sandbox Code Playgroud)
但是当我检查json变量时,它包含类似下面的空值
{"我的钥匙":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{} {},{},{},{},{},{},{}]}
当我检查attrs变量时,它包含22个元素Data.What我在做错了吗?我只是将我的List转换为Json对象并保存到数据库.我在用
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
Run Code Online (Sandbox Code Playgroud)
您可以使用下面的代码
public String listToJsonString(List<StyleAttribute> attrs) {
JSONObject jObject = new JSONObject();
try {
JSONArray jArray = new JSONArray();
for (MyClass myObject: attrs) {
JSONObject styleJSON = new JSONObject();
styleJSON.put("name",myObject.getName());
styleJSON.put("rollNumber", myObject.getRollNumber());
jArray.add(styleJSON);
}
jObject.put("keyName", jArray);
} catch (Exception jse) {
}
return jObject.toString();
}
Run Code Online (Sandbox Code Playgroud)
它将解决您的问题。
归档时间: |
|
查看次数: |
6204 次 |
最近记录: |