I want to parse these kind of Json responses :
{
"MyResponse": {
"count": 3,
"listTsm": [{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 1,
"name": "vignesh1"
},
{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 2,
"name": "vignesh2"
},
{
"id": "b90c6218-73c8-30bd-b532-5ccf435da766",
"simpleid": 3,
"name": "vignesh3"
}]
}
}
I tried using SIMPLE JSON parser but this is not working for me:
Object obj = parser.parse(resp);
JSONObject jsonObject = (JSONObject) obj;
JSONArray response = (JSONArray) jsonObject.get("MyResponse");
//JSONArray arr=new JSONArray(yourJSONresponse);
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<response.size(); i++){
list.add(response.get(i)("name"));
}
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
JSON Processing in Java : The Java API for JSON Processing JSON. simple is a simple Java library that allow parse, generate, transform, and query JSON.
To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.
public interface JsonParser extends Closeable. Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. The class Json contains methods to create parsers from input sources ( InputStream and Reader ).
public static void main(String[] args) throws JSONException {
String jsonString = "{" +
" \"MyResponse\": {" +
" \"count\": 3," +
" \"listTsm\": [{" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 1," +
" \"name\": \"vignesh1\"" +
" }," +
" {" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 2," +
" \"name\": \"vignesh2\"" +
" }," +
" {" +
" \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," +
" \"simpleid\": 3," +
" \"name\": \"vignesh3\"" +
" }]" +
" }" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject myResponse = jsonObject.getJSONObject("MyResponse");
JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<tsmresponse.length(); i++){
list.add(tsmresponse.getJSONObject(i).getString("name"));
}
System.out.println(list);
}
}
Output:
[vignesh1, vignesh2, vignesh3]
Comment: I didn't add validation
[EDIT]
other way to load json String
JSONObject obj= new JSONObject();
JSONObject jsonObject = obj.fromObject(jsonString);
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With