Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Tonity's solution is good. You can also use this solution.</p> <p>In my solution, there will be no any <strong>Exception</strong> fired <strong>until JSON is wrong</strong>. What I am doing is following.</p> <blockquote> <ol> <li>Search for number of ":" in string. </li> <li>If it returns 1, then we sure that there is "name" value.</li> <li>Otherwise, we need to check, whether there is "FirstName","MiddleName" or "LastName" exist in string or not.</li> </ol> </blockquote> <p>Just go through this snippet and you will find solution for your problem.</p> <pre><code>// String str = "{\"name\":\"chintan\"}"; String str = "{\"name\":{\"FirstName\":\"Chintan\",\"LastName\":\"Rathod\"}}"; try { //we will check how many ":" are there in string, if it is one, then // we are going to get "name" field. if ((str.split(":").length - 1) == 1) { Log.d("Home", "1"); JSONObject json = new JSONObject(str); Log.d("Home", "Name : " + json.get("name")); } else { Log.d("Home", "more then 2"); JSONObject jName = new JSONObject(str); JSONObject jTemp = jName.getJSONObject("name"); if (jTemp.toString().contains("FirstName")) Log.d("Home", "FirstName :" + jTemp.getString("FirstName")); if (jTemp.toString().contains("MiddleName")) Log.d("Home","MiddleName :" +jTemp.getString("MiddleName")); if (jTemp.toString().contains("LastName")) Log.d("Home", "LastName :" + jTemp.getString("LastName")); } } catch (JSONException e) { e.printStackTrace(); } </code></pre> <p><strong>Output</strong></p> <pre><code>08-06 11:52:34.060: D/Home(1439): more then 2 08-06 11:52:34.060: D/Home(1439): FirstName :Chintan 08-06 11:52:34.070: D/Home(1439): LastName :Rathod </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload