Json string:
{
"event": {
"event_name": "Customer Phone Number",
"operation_type": "Add",
"transaction_identifier": "1234567890",
"event_publication_timestamp_millis": "1518464452915",
"event_publisher": "CIS",
"event_publisher_identity": "System",
"event_timestamp_millis": "NONE",
"event_initiator": "NONE",
"event_initiator_identity": "NONE"
},
"contents": [
{
"data_group_name": "customer_identifier",
"data_fields": [
{
"data_field_name": "company_number",
"data_field_type": "string",
"data_field_value": "069"
},
{
"data_field_name": "customer_short_name",
"data_field_type": "string",
"data_field_value": "marshben"
},
{
"data_field_name": "tie_breaker",
"data_field_type": "string",
"data_field_value": "01"
}
]
},
{
"data_group_name": "customer_phone_number",
"data_fields": [
{
"data_field_name": "phone_number",
"data_field_type": "string",
"data_field_value": "555-1212"
},
{
"data_field_name": "phone_type",
"data_field_type": "string",
"data_field_value": "cell"
},
{
"data_field_name": "primary_indicator",
"data_field_type": "string",
"data_field_value": "yes"
}
]
}
]
}
JSONObject rootObject = new JSONObject(result);
System.out.println("this");
System.out.println(rootObject.toString());
上面的代码只给出了内容的一部分,如何获取以事件开头的顶级数据。
Here is the output of :
"contents": [
{
"data_group_name": "customer_identifier",
"data_fields": [
{
"data_field_name": "company_number",
"data_field_type": "string",
"data_field_value": "069"
},
{
"data_field_name": "customer_short_name",
"data_field_type": "string",
"data_field_value": "marshben"
},
{
"data_field_name": "tie_breaker",
"data_field_type": "string",
"data_field_value": "01"
}
]
},
{
"data_group_name": "customer_phone_number",
"data_fields": [
{
"data_field_name": "phone_number",
"data_field_type": "string",
"data_field_value": "555-1212"
},
{
"data_field_name": "phone_type",
"data_field_type": "string",
"data_field_value": "cell"
},
{
"data_field_name": "primary_indicator",
"data_field_type": "string",
"data_field_value": "yes"
}
]
}
]
}
我想解析每个元素并读取值。但是json对象只解析字符串的一部分。处理这个字符串的最佳途径是什么。 从事件开始的顶级部分非常重要。
答案 0 :(得分:0)
对于该示例,您共享我可以看到所有元素都在rootObject变量中。它的顺序已经改变了。
您的输入JSON具有这样的结构
{
"event": {..},
"contents": [..]
}
在创建和输出JSON对象时,它会变成这样:
{
"contents": [..],
"event": {..}
}
意味着所有字段都在JSONObject中,但只是订单已更改,这是预期的,因为没有必要按照JSON规范维护字段的顺序。您可以通过按字段名称解析来验证字段确实存在。对于上面的例子:
System.out.println(rootObject.get("event").toString());