从json文件中获取属性值



我使用Java语言。我想打印名称,MACAddress,active,uniqueDeviceIdentifier值在同一行上。我已经尝试了下面的代码,但我无法获取名称,我能够获取其余的属性,我正在努力与名称属性

test.json

{
"names": [
{
"name": "ABC",
"thingTypeName": "SmartPhone",
"attributes": {
"MACAddress": "02:00:00:44:11:30",
"active": "true"
},
"version": 1
},
{
"name": "XYZ",
"thingTypeName": "SmartPhone",
"attributes": {
"active": "true",
"uniqueDeviceIdentifier": "2EAFCEE9-6379-4010-B6B1-8F335D83316F"
},
"version": 38
},
{
"name": "YYZ",
"thingTypeName": "SmartPhone",
"attributes": {
"active": "true",
"uniqueDeviceIdentifier": "2EAFCEE9-6379-4010-B6B1-8F335D833161"
},
"version": 39
},
{
"name": "AAA",
"thingTypeName": "SmartPhone",
"attributes": {
"MACAddress": "02:00:00:44:55:32"
},
"version": 1
}
]
}
JSONParser jsonParser = new JSONParser();
Object object;
try {
object = jsonParser.parse(new FileReader("src/main/resources/Test.json"));
JSONObject jsonObject = (JSONObject) object;
JSONArray things = (JSONArray) jsonObject.get("things");
Iterator itr = things.iterator();
System.out.println("thing name"+"^"+"mac Address"+"^"+"activation Code"+"^"+"unique Device Identifier");
while (itr.hasNext()) {
Object slide = itr.next();
JSONObject jsonObject2 = (JSONObject) slide;
JSONObject attributes = (JSONObject) jsonObject2.get("attributes");
String macAddress = (String) attributes.get("MACAddress");
String activationCode = (String) attributes.get("activationCode");
String uniqueDeviceIdentifier = (String) attributes.get("uniqueDeviceIdentifier");       System.out.println(macAddress+"^"+activationCode+"^"+uniqueDeviceIdentifier);

要求输出

name^MACAddress^active^uniqueDeviceIdentifier
ABC^02:00:00:44:11:30^true^null
XYZ^null^true^2EAFCEE9-6379-4010-B6B1-8F335D83316F
YYZ^null^true^2EAFCEE9-6379-4010-B6B1-8F335D833161
XYZ^02:00:00:44:55:32^null^null
JSONParser jsonParser = new JSONParser();
Object object;
try {
object = jsonParser.parse(new FileReader("src/main/resources/thing.json"));
JSONObject jsonObject = (JSONObject) object;

JSONArray things = (JSONArray) jsonObject.get("things");

Iterator itr = things.iterator();
System.out.println("Thing_name"+"^"+"Mac_Address"+"^"+"Active"+"^"+"Unique_Device_Identifier");
JSONArray jsonArray = (JSONArray) jsonObject.get("things");
while (itr.hasNext()) {
//                JSONArray attributes1 = (JSONArray) jsonObject.get("thingName");
for (int i = 0; i <jsonArray.size(); i++) {
Object slide = itr.next();
JSONObject jsonObject2 = (JSONObject) slide;
JSONObject attributes = (JSONObject) jsonObject2.get("attributes");
String macAddress = (String) attributes.get("MACAddress");
String active = (String) attributes.get("activationCode");
String uniqueDeviceIdentifier = (String) attributes.get("uniqueDeviceIdentifier");
System.out.println(((JSONObject) jsonArray.get(i)).get("thingName") + "^" + macAddress + "^" + active + "^" + uniqueDeviceIdentifier);

最新更新