本文介绍了如何将数据列表转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要以下json,其中 List< form>
将包含 form_id
的列表, form_name
,如何使用jsonobject转换它,我没有得到正确的json输出。请帮我解决一下这个。
Json:
I want the following json ,where List<form>
will have list of form_id
,form_name
, how can I convert this using jsonobject, I am not getting the proper json output. Please help me with this.Json:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
上面是我需要它的json结构列表。其中id,name是来自表单对象的列表
The above is the json structure that i need it for a list.Where id ,name is a list from form object
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
此处面临的问题是不将输出作为列表
Facing issue here not getting output as a list
推荐答案
原始问题中的代码接近于实现所描述的期望结果。只需在循环外移动 JSONArray
实例创建。
The code in the original question is close to achieving the described desired result. Just move the JSONArray
instance creation outside of the loop.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Foo
{
public static JSONObject getJsonFromMyFormObject(List<Form> form)
{
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < form.size(); i++)
{
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson;
}
public static void main(String[] args)
{
List<Form> forms = new ArrayList<Form>();
forms.add(new Form("1", "test1"));
forms.add(new Form("2", "test2"));
JSONObject jsonObject = getJsonFromMyFormObject(forms);
System.out.println(jsonObject);
}
}
class Form
{
String id;
String name;
Form(String i, String n)
{
id = i;
name = n;
}
String getId()
{
return id;
}
String getName()
{
return name;
}
}
这篇关于如何将数据列表转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!