我应该准备哪些java类结构来返回这样的JSON?
更正了JSON(高于一个无效):
{
"transactionComparisonTotals": [
[
"CurrentFace",
{
"value": "1000000",
"format": "$000.00 ptr"
},
{
"value": "1000",
"format": "$000.00 ptr"
},
{
"value": "0",
"format": "$000.00 ptr"
}
],
[
"MarketPrincipal",
{
"value": "1000000",
"format": "$000.00 ptr"
},
{
"value": "1000",
"format": "$000.00 ptr"
},
{
"value": "0",
"format": "$000.00 ptr"
}
]
]
}
为此我需要一组java类。 0
所以我能做的一件事就是生成JSON,如:
{
"transactionComparisonTotals": [
{
"key": "coupon",
"valueAttributes": [
{
"value": 4.25,
"format": "00.00%",
"color": true,
"sign": true
},
{
"value": 4.26,
"format": "$00.00 %",
"color": true,
"sign": true
},
{
"value": 0.31,
"format": "00.00 bp",
"color": true,
"sign": true
}
]
}
}
但我真正想要的是在一个没有属性的数组中使用“Key”和“valueAttributes”(如我原来的JSON所示)。
答案 0 :(得分:2)
考虑这个json文件transaction.json
:(你的文件是无效的,所以我试图纠正它只是为了获得使用gson google API进行序列化和去除化的想法)。
{
"transactionComparisonTotals": [
{
"name": "CurrentFace",
"info":
[
{
"value": "1000000",
"format": "$000.00 ptr"
},
{
"value": "1000",
"format": "$000.00 ptr"
},
{
"value": "0",
"format": "$000.00 ptr"
}
]
},
{
"name": "MarketPrincipal",
"info":
[
{
"value": "1000000",
"format": "$000.00 ptr"
},
{
"value": "1000",
"format": "$000.00 ptr"
},
{
"value": "0",
"format": "$000.00 ptr"
}
]
}
]
}
创建这些类:
数据类:
public class Data{
List<TransactionComparisonTotal> transactionComparisonTotals;
public List<TransactionComparisonTotal> getTransactionComparisonTotals() {
return transactionComparisonTotals;
}
public void setTransactionComparisonTotals(
List<TransactionComparisonTotal> transactionComparisonTotals) {
this.transactionComparisonTotals = transactionComparisonTotals;
}
@Override
public String toString() {
return transactionComparisonTotals.toString();
}
}
TransactionComparisonTotal class:
public class TransactionComparisonTotal{
String name;
List<Info> info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Info> getInfo() {
return info;
}
public void setInfo(List<Info> info) {
this.info = info;
}
@Override
public String toString() {
return "\n"+name+","+info.toString()+"\n";
}
}
信息类:
public class Info{
String value;
String format;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public String toString() {
return value+","+format;
}
}
这是使用gson google API
进行去血污染的简单示例public class Transaction {
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
Gson gson = new Gson();
Data data = gson.fromJson(new BufferedReader(new FileReader(
"transaction.json")), new TypeToken<Data>() {
}.getType());
System.out.println(data);
}
}
输出:
[
CurrentFace,[1000000,$000.00 ptr, 1000,$000.00 ptr, 0,$000.00 ptr]
,
MarketPrincipal,[1000000,$000.00 ptr, 1000,$000.00 ptr, 0,$000.00 ptr]
]