[英]Java - Read data from a json with the JSON library according to an object
I have a JSON with some data and I would like to print as follows我有一个带有一些数据的 JSON,我想打印如下
10 REGISTER 1, KP SUM 2081,606
20 REGISTER 2 CH SUM 0,22
Where the general sum is calculated by the total sum of the items according to the code.其中,总和是按代码规定的项目总和计算的。
Following the rule, first multiply the quantity by the unit and then add all the items that have the same code.按照规则,首先将数量乘以单位,然后将具有相同代码的所有项目相加。
Example:例子:
code 10
SUM = 0,0200000 * 7,40 + 10,0000000 * 200,31 + 0,5690000 * 40,19 + 0,7890000 * 70,33
The same goes for the other codes that appear in JSON JSON 中出现的其他代码也是如此
My JSON我的 JSON
[
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"itemCode": 1,
"descriptionItem": "ITEM",
"unityItem": "UN",
"quantity": "0,0200000",
"valueUnity": "7,40"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "UN",
"quantity": "10,0000000",
"valueUnity": "200,31"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88248,
"descriptionItem": "ITEM 3",
"unityItem": "H",
"quantity": "0,5690000",
"valueUnity": "40,19"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88267,
"descriptionItem": "ITEM 4",
"unityItem": "N",
"quantity": "0,7890000",
"valueUnity": "70,33"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 1,
"descriptionItem": "ITEM 1",
"unityItem": "H",
"quantity": "30,0000000",
"valueUnity": "0,17"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "H",
"quantity": "3,0000000",
"valueUnity": "0,07"
}
]
My class Java我的 class Java
public class MyJson {
@SerializedName("code")
@Expose
private Integer code;
@SerializedName("description")
@Expose
private String description;
@SerializedName("unity")
@Expose
private String unity;
@SerializedName("typeItem")
@Expose
private String typeItem;
@SerializedName("codeItem")
@Expose
private Integer codeItem;
@SerializedName("descriptionItem")
@Expose
private String descriptionItem;
@SerializedName("unityItem")
@Expose
private String unityItem;
@SerializedName("quantity")
@Expose
private String quantity;
@SerializedName("valueUnity")
@Expose
private String valueUnity;
private Double total;
}
My Program我的程序
public static void main(String[] args) {
Gson gson = new Gson();
try {
File jsonFile = new File("C:\\my_json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
MyJson[] myJsonArray = gson.fromJson(jsonBuffer, MyJson[].class);
BigDecimal valueUnity = BigDecimal.ZERO;
BigDecimal sumTotal = BigDecimal.ZERO;
//
Set<MyJson> list = new HashSet<>();
for(MyJson myJson : myJsonArray) {
if(checkStringNullOrEmpty(myJson.getQuantity()) && checkStringNullOrEmpty(myJson.getValueUnity())) {
if(myJson.getCode().equals(myJson.getCode())) {
String value1 = myJson.getQuantity().replaceAll( "," , "." ).trim();
String value2 = myJson.getValueUnity.replaceAll( "," , "." ).trim();
BigDecimal quantity = new BigDecimal(value1);
BigDecimal valueUnit = new BigDecimal(value2);
valueUnity = quantity.multiply(valueUnit);
somaTotal = sumTotal.add(valueUnity);
String resultado = String.format(Locale.getDefault(), "%.2f", valueUnity);
String sumTotal2 = String.format(Locale.getDefault(), "%.2f", sumTotal);
myJson.setTotal(new Double(sumTotal2.replaceAll( "," , "." ).trim()));
list.add(myJson);
}
}
}
for(MyJson myJson : list) {
StringBuilder builer = new StringBuilder();
builer.append(myJson.getCode()).append(" ");
builer.append(myJson.getDescription().toUpperCase()).append(" ");
builer.append(myJson.getUnity().toUpperCase()).append(" ");
builer.append(myJson.getTotal());
System.out.println(builer.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkStringNullOrEmpty(String value) {
if(!value.isEmpty()) {
return true;
} else {
return false;
}
}
Exit program
The calculation is being done wrong when using the Set使用 Set 时计算错误
10 REGISTER 1, KP SUM 130,33
20 REGISTER 2 CH SUM 439,18
You cannot keep track of multiple running totals (ie one for each code) using one total.您无法使用一个总计来跟踪多个运行总计(即每个代码一个)。 Instead you will need one total for each different code.相反,您需要为每个不同的代码提供一个总数。
I would recommend that you use a Map<Integer, MyJson>
for this purpose.为此,我建议您使用Map<Integer, MyJson>
。 This would store a number of MyJson
objects which you could look up by their code.这将存储许多MyJson
对象,您可以通过它们的代码查找这些对象。 When handling each MyJson
object, you check to see if you already have a MyJson
object with the same code: if you do then you add to its total, otherwise you add your MyJson
object to the map. When handling each MyJson
object, you check to see if you already have a MyJson
object with the same code: if you do then you add to its total, otherwise you add your MyJson
object to the map.
Get rid of your Set<MyJson>
variable (which you have somewhat confusingly named list
) and replace it with the following摆脱您的Set<MyJson>
变量(您的名称有点混乱list
)并将其替换为以下内容
Map<Integer, MyJson> jsonsByCode = new LinkedHashMap<>();
(You can use a HashMap<>
instead of a LinkedHashMap<>
here: I chose to use a LinkedHashMap<>
because it keeps its entries in the same order they were inserted into it.) (您可以在这里使用HashMap<>
而不是LinkedHashMap<>
:我选择使用LinkedHashMap<>
因为它的条目与插入时的顺序相同。)
Then, replace all lines from somaTotal = sumTotal.add(valueUnity);
然后,替换somaTotal = sumTotal.add(valueUnity);
中的所有行to list.add(myJson);
到list.add(myJson);
with和
if (jsonsByCode.containsKey(myJson.getCode())) {
// We've seen this code before, so add the value
// to the total.
MyJson matchingJson = jsonsByCode.get(myJson.getCode());
matchingJson.setTotal(matchingJson.getTotal() + valueUnity.doubleValue());
} else {
// First time seeing this code, so set its total
// and add it to the map.
myJson.setTotal(valueUnity.doubleValue());
jsonsByCode.put(myJson.getCode(), myJson);
}
(Note that BigDecimal
values such as valueUnity
have a .doubleValue()
method on them, which is the easiest way to convert them to a double
.) (请注意,像valueUnity
这样的BigDecimal
值有一个.doubleValue()
方法,这是将它们转换为double
的最简单方法。)
Then, in the for
loop below, where you are printing out the values, replace list
with jsonsByCode.values()
.然后,在下面的for
循环中,您将在其中打印出值,将list
替换为jsonsByCode.values()
。
I made these changes to your program and it generated the following output:我对您的程序进行了这些更改,它生成了以下 output:
10 REGISTER 1 KP 2081.60648
20 REGISTER 2 CH 5.31
if
statement:
顺便说一句,您的代码还包含以下if
语句:
if(myJson.getCode().equals(myJson.getCode())) { //.... }
You are comparing myJson.getCode()
against itself, so this condition will always be true
(unless of course myJson.getCode()
returns null
, in which case you get a NullPointerException
).您正在将myJson.getCode()
与自身进行比较,因此此条件将始终为true
(当然,除非myJson.getCode()
返回null
,在这种情况下您会得到NullPointerException
)。 You can just get rid of this check, it doesn't do anything useful.你可以摆脱这个检查,它没有做任何有用的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.