package com.xxx.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* @author yangxin-ryan
*/
public class StringUtil {
/**
* 测试的man方法
* @param args
*/
public static void main(String[] args) {
// 原始字符串数据
String str = "[{\"metric\":\"base.app.dns.1m\",\"tags\":{\"platform\":\"xxx\"},\"aggregateTags\":[],\"dps\":{\"1519698960\":800.0}},{\"metric\":\"base.app.dns.1m\",\"tags\":{\"platform\":\"zzzz\"},\"aggregateTags\":[],\"dps\":{\"1519698960\":800.0}},{\"metric\":\"base.app.dns.1m\",\"tags\":{\"platform\":\"b2Zv5bCP6buE6L2m\"},\"aggregateTags\":[],\"dps\":{\"1519698960\":1000.0}}]\n";
// 字符串转换为JSON数组
JSONArray json = JSONArray.fromObject(str);
// 获取数组中的第一个JSON元素
System.out.println(json.getJSONObject(0));
// 获取 JSON 元素中二级 key 为 platform 的值
System.out.println(json.getJSONObject(0).getJSONObject("tags").get("platform"));
// 获取所有的 key,是 keys() 方法,这里是取第一个 key
String timestamp = json.getJSONObject(0).getJSONObject("dps").keys().next().toString();
// 根据 key 取数据
System.out.println(json.getJSONObject(0).getJSONObject("dps").get(timestamp));
}
}
结果
![](https://img.haomeiwen.com/i14653704/72153a76fd48f7b8.png)
网友评论