It is often necessary to convert a string to a JSON type for practical use
The String is converted to a JSON object
public class Str2Json {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}";
JSONObject json;
json = JSON.parseObject(str);
System.out.println(json);
}
}
Copy the code
Output results:
{"cases":[{"classname":"HttpGet","url":"https://www.baidu.com"},{"classname":"HttpPost","url":"https:www.qq.com"}]}
Copy the code
From the results, it looks like STR and JSON are not very different, but the method supported by JSON has changed, and the relevant content can be extracted directly from JSON. The details are as follows:
public class Str2Json {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}";
JSONObject json;
json = JSON.parseObject(str);
System.out.println(json.getString("cases"));
}
}
Copy the code
Output results:
[{"classname":"HttpGet","url":"https://www.baidu.com"},{"classname":"HttpPost","url":"https:www.qq.com"}]
Copy the code
There are other methods, just use them as needed. For example, json.getJsonArray (“cases”) can be directly converted to the list type
Turn the String JSONArray
public class Str2Json {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}";
JSONObject json;
json = JSON.parseObject(str);
String jsonstr = json.getString("cases");
System.out.println(JSONArray.parseArray(jsonstr));
}
}
Copy the code
Output results:
[{"classname":"HttpGet","url":"https://www.baidu.com"},{"classname":"HttpPost","url":"https:www.qq.com"}]
Copy the code
You can think of jSONstr as a String, and it’s a little difficult to get the full elements in it, but when you convert it to a JSONArray, it’s similar to using a list element
public class Str2Json {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}";
JSONObject json;
json = JSON.parseObject(str);
String jsonstr = json.getString("cases");
System.out.println(JSONArray.parseArray(jsonstr).get(0));
}
}
Copy the code
Output results:
{"classname":"HttpGet","url":"https://www.baidu.com"}
Copy the code
Easily get the data you need based on the index.