我想一次性读取一个json对象。我写的代码是读取json但不是以相同的顺序。
我在json的数据是:
{
"protocolDate":"2014-09-08",
"spName":"UL",
"testId":"123",
"productDescription":"Refrigerator-Freezer",
"protocolType":"Test Protocol Template",
"sampleSize":"1",
"protocolName":"Refrigerator-Freezer"}
我的代码是:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./NewTestImport.json"));
JSONObject jsonObject = (JSONObject) obj;
String protocolDate = (String) jsonObject.get("protocolDate");
String spName = (String) jsonObject.get("spName");
String testId = (String) jsonObject.get("testId");
String productDescription = (String) jsonObject.get("productDescription");
String protocolType = (String) jsonObject.get("protocolType");
String sampleSize = (String) jsonObject.get("sampleSize");
String protocolName = (String) jsonObject.get("protocolName");
List<Map<String,String>> data= new ArrayList<Map<String,String>>();
data.add(jsonObject);
我不想明确初始化每个json对象。
答案 0 :(得分:0)
我刚修改了你的代码,
Map<String,String>jso = new LinkedHashMap<String,String>();
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./NewTestImport.json"));
JSONObject jsonObject = (JSONObject) obj;
jso.put("protocolDate", (String) jsonObject.get("protocolDate"));
jso.put("spName", (String) jsonObject.get("spName"));
jso.put("testId", (String) jsonObject.get("testId"));
jso.put("productDescription", (String) jsonObject.get("productDescription"));
jso.put("protocolType", (String) jsonObject.get("protocolType"));
jso.put("sampleSize", (String) jsonObject.get("sampleSize"));
jso.put("protocolName", (String) jsonObject.get("protocolName"));
List<Map<String,String>> data= new ArrayList<Map<String,String>>();
data.add(jso);
System.out.println(data);
输出:
[{protocolDate=2014-09-08, spName=UL, testId=123, productDescription=Refrigerator-Freezer, protocolType=Test Protocol Template, sampleSize=1, protocolName=Refrigerator-Freezer}]
答案 1 :(得分:-1)
你可以在这里使用Gson是一个很好的链接gson api
在这里你可以看到简单的例子
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);