jsonObject里有bigDecimal类型数据和String数据,在不知道字段类型的情况下,只获取bigDecimal类型数据 java
时间: 2024-02-17 13:05:22 浏览: 96
可以通过遍历JSON对象的所有字段来判断每个字段的数据类型,从而获取BigDecimal类型的数据。
以下是一个示例代码,假设JSON对象为jsonObject:
```
import java.math.BigDecimal;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject("{ 'number': 123.456, 'string': 'hello' }");
BigDecimal number = null;
for (String key : jsonObject.keySet()) {
try {
Object value = jsonObject.get(key);
if (value instanceof BigDecimal) {
number = (BigDecimal) value;
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("Number: " + number);
}
}
```
在以上示例代码中,我们通过遍历JSON对象的所有字段,判断每个字段的数据类型是否为BigDecimal类型,如果是则将该字段的值赋给变量number并跳出循环。需要注意的是,由于JSON对象中的值都是以Object类型存储的,因此需要使用`instanceof`关键字来判断数据类型。
阅读全文
相关推荐


















