我遇到了异常,
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "Instrument1"
这里是 JSON
[{
"_id":"INS_123",
"global_us":{
"ProductID":"INS_123",
"ProductNameGlobal":"Instrument1",
"Brand Name":"Brand",
"ProductType":"Instrument",
"Status":"Avail",
"Channel":"Channel",
"InstrumemtCode":"Instrument1",
"LifeCycleStatus":""
},
"en_us":{
"ProductID":"INS_123",
"ProductNameGlobal":"Instrument1",
"Brand Name":"Brand",
"ProductType":"Instrument",
"Status":"Avail",
"Channel":"Channel",
"InstrumemtCode":"Instrument1",
"LifeCycleStatus":""
}
},
{
"_id":"INS_124",
"global_us":{
"ProductID":"INS_124",
"ProductNameGlobal":"Instrument2",
"Brand Name":"Brand",
"ProductType":"Instrument",
"Status":"Avail",
"Channel":"Channel",
"InstrumemtCode":"Instrument2",
"LifeCycleStatus":""
},
"en_us":{
"ProductID":"INS_124",
"ProductNameGlobal":"Instrument2",
"Brand Name":"Brand",
"ProductType":"Instrument",
"Status":"Avail",
"Channel":"Channel",
"InstrumemtCode":"Instrument2",
"LifeCycleStatus":""
}
}
]
在我的代码中,我们有两个 POJO 类和一个 Read Json 业务类
public class Product {
private Global global_us;
public Global getGlobal_us() {
return global_us;
}
public void setGlobal_us(Global global_us) {
this.global_us = global_us;
}
private String ProductID;
private int ProductGlobalName;
public String getProductID() {
return ProductID;
}
public void setProductID(String productID) {
ProductID = productID;
}
public int getProductGlobalName() {
return ProductGlobalName;
}
public void setProductGlobalName(int productGlobalName) {
ProductGlobalName = productGlobalName;
}
}
全局.java
public class Global {
private String ProductID;
private int ProductNameGlobal;
public String getProductID() {
return ProductID;
}
public void setProductID(String productID) {
ProductID = productID;
}
public int getProductNameGlobal() {
return ProductNameGlobal;
}
public void setProductNameGlobal(int productNameGlobal) {
ProductNameGlobal = productNameGlobal;
}
}
还有一个业务逻辑类ReadJson.java
package com.test.practice.gson;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class ReadJson {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\json\\productlist.json")) {
// Convert JSON to Java Object
Product[] productList = gson.fromJson(reader, Product[].class);
for (Product product : productList) {
System.out.println(product.getGlobal_us().getProductNameGlobal());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
已经提出了几个与此相关的问题,但这些问题是针对数字或 double 值的。在我的 json 中,我有字符串+数字。
任何人都可以帮忙解决这个问题吗?
最佳答案
这是因为 ProductNameGlobal
属性在您的 Global
类中是 int 类型。在 JSON 中,您将传递该字段的字符串值 "ProductNameGlobal":"Instrument1"
。
如果您的业务逻辑允许,您可能需要将 ProductNameGlobal
类型更改为 String
。
关于java - 解析 json 时 GSON 中的数字格式异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139882/