下面的代码正确生成了 json 文件的第一个结构。
gson = new GsonBuilder().setPrettyPrinting().create();
AudDetHeader AudDetHeader = new AudDetHeader();
//ArrayList<OrderDetail> AudDetList = new ArrayList<OrderDetail>();
Map<String, AudDet> AudDetList = new HashMap<String, AudDet>();
AudDet AudDet = new AudDet();
AudDet.setLineId("1");
AudDet.setItemNumber("ABC");
AudDet.setQuantity(9);
AudDet.setPrice(10.00);
List<String> phones = new ArrayList<String>();
phones.add("24530001");
phones.add("24530002");
phones.add("24530003");
AudDet.setPhones(phones);
AudDetList.put("teste 2", AudDet);
AudDetHeader.setAudDetList(AudDetList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(AudDetHeader);
BufferedWriter bufferedWriter = null;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
代码结果:
{
"Results": {
"teste 2": {
"itemNumber": "ABC",
"lineId": "1",
"phones": [
"24530001",
"24530002",
"24530003"
],
"price": 10.0,
"quantity": 9
}
}
}
我想添加一个新项目。我的愿望是保持下面的结构。
{
"Results":{
"teste 2":{
"itemNumber":"ABC",
"lineId":"1",
"phones":[
"24530001",
"24530002",
"24530003"
],
"price":10.0,
"quantity":9
},
"teste 3":{
"itemNumber":"DEF",
"lineId":"2",
"phones":[
"30303030",
"40404040",
"505050"
],
"price":11.0,
"quantity":12
}
}
}
AudDetHeader.class
public class AuditoriaDetalheHeader {
@SerializedName("Results")
private Map<String, AuditoriaDetalhe> AuditoriaDetalheList;
...
}
AudDet 类
public class AuditoriaDetalhe {
String lineId = null;
String itemNumber = null;
int quantity = 0;
Double price = null;
List<String> phones = new ArrayList<String>();
...
}