import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.springframework.util.StopWatch;
public class GsonUtils2 {
private static Gson gson = new Gson();
public static void main(String[] args) {
String jsonStr="{\"name\":\"张三\",\"age\":18,\"address\":{\"province\":\"广东省\",\"city\":\"深圳市\",\"district\":\"南山区\"},\"hobbies\":[\"篮球\",\"游泳\",\"旅游\"]}";
StopWatch sw=new StopWatch();
sw.start("递归输出json所有key和value");
JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
getAllKeys(jsonObject, "");
sw.stop();
System.out.println("总共耗时:" + sw.getTotalTimeMillis() + "ms");
}
public static void getAllKeys(JsonObject jsonObject, String parentKey) {
for (String key : jsonObject.keySet()) {
JsonElement value = jsonObject.get(key);
StringBuffer sb=new StringBuffer();
sb.append(parentKey).append(key).append(".");
if (value.isJsonObject()) {
getAllKeys(value.getAsJsonObject(), sb.toString());
} else if (value.isJsonArray()) {
getAllKeys(value.getAsJsonArray(), sb.toString());
} else {
StringBuffer newSb=new StringBuffer();
newSb.append(parentKey).append(key).append(":").append(value.getAsString());
System.out.println(newSb);
}
}
}
public static void getAllKeys(JsonArray jsonArray, String parentKey) {
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement value = jsonArray.get(i);
StringBuffer sb=new StringBuffer();
sb.append(parentKey).append("[").append(i).append("]").append(".");
if (value.isJsonObject()) {
getAllKeys(value.getAsJsonObject(), sb.toString());
} else if (value.isJsonArray()) {
getAllKeys(value.getAsJsonArray(), sb.toString());
} else {
StringBuffer newSb=new StringBuffer();
newSb.append(parentKey).append("[").append(i).append("]").append(":").append(value.getAsString());
System.out.println(newSb);
}
}
}
}