Mined and Summarized Use Cases For API: org.json

  1. How to parse JSON in Java

    Example code is as below You may find extra examples from Parse-JSON-in-Java . . .. details

    1. static Object jsonParser(String jsonStr, String key) throws JSONException { int i = 0
    2. Object temp = null
    3. Object json = new JSONObject(jsonStr)
    4. String[] keys = key.split("[.]")
    5. while (i < keys.length) { if (json instanceof JSONArray) { int index = Integer.parseInt(keys[i])
    6. temp = ((JSONArray) json).get(index)
    7. } else if (json instanceof JSONObject) { temp = ((JSONObject) json).get(keys[i])
    8. } json = temp
    9. i++
    10. } return temp
    11. }

    Positive Reactions
    1. It's generally a good idea to explain _why_ your code answers the question.

    • See Also (33)
    1. Android JSON Parsing And Conversion

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private void read_JSON(String json) { JSONObject jObject= new JSONObject(json)
      2. JSONArray jso3= new JSONArray(jObject.getString("Nombres_Hijos"))
      3. for (int i=0
      4. i < jso3.length()
      5. i++) { try { String name = jso3.getString("Nombre")
      6. String surname = jso3.getString("Apellidos")
      7. String date = jso3.getString("Ao_nacimiento")
      8. String child_names = jso3.getString("Nombres_Hijos")
      9. }catch (JSONException e) { e.printStackTrace()
      10. } } jso3.toString(JSON)
      11. }

    2. How to parse from this JSONString?

      This will work. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. try{JSONArray json = new JSONArray(str)
      2. for(int i = 0
      3. i< json.length()
      4. i++){ JSONObject c1 = (JSONObject) json.get(i)
      5. JSONArray spritPrice = c1.getJSONArray("spritPrice")
      6. for (int j = 0
      7. j < spritPrice.length()
      8. j++) { JSONObject c2 = (JSONObject) spritPrice.get(j)
      9. String amount = c2.getString("amount")
      10. System.out.println(amount)
      11. }}}catch (JSONException e){e.printStackTrace()
      12. }

    3. How to parse from this JSONString?

      This is how I get strings from jsonarray try to do it . Try this . details

      Reactions - Positive 2, Negative 0, Others 0

      1. // ArrayList<String> amountList=new ArrayList<String>()
      2. String amount=null
      3. try { // Getting JSON Array String your_json_response
      4. JSONArray responseArray = new JSONArray(your_json_response)
      5. for(int j=0
      6. j<responseArray.length()
      7. j++) { JSONArray spritPrice=responseArray.getJSONObject(i).JSONArray("spritPrice")
      8. int spritPrice= spritPrice.length()
      9. for(int i=0
      10. i < spritPrice
      11. i++ ){ JSONObject c = spritPrice.getJSONObject(i)
      12. amount = c.getString("amount")
      13. // amountList.add(amount)
      14. System.out.println(amount)
      15. if(amount!=null) break
      16. } if(amount!=null) break
      17. } } catch (JSONException e) { e.printStackTrace()
      18. }

      Positive Reactions
      1. Now it's working.
      2. nice.
      Other Reactions
      1. It gives me 10 times the first price.
      2. I edit your post and then I accept it.
      3. I changed something.

    4. How to parse from this JSONString?

      voteup my answer if it has helped you any way ). This is how I get strings from jsonarray try to do it . details

      Reactions - Positive 0, Negative 0, Others 0

      1. try { JSONArray spritPriceArr = jObj.getJSONArray("spritPrice")
      2. int spritPriceArrLength = spritPriceArr.length()
      3. String[] StringofAmount = new Strng[spritPriceArrLength] for(int i=0
      4. i < spritPriceArrLength
      5. i++ ){ JSONObject c = spritPriceArr.getJSONObject(i)
      6. StringofAmount[i] = c.optString("amount")
      7. }} catch (JSONException e) { e.printStackTrace()
      8. }

    5. JSON Responce data Getting at Console i used Java,Eclipse,Tomcat

      . Here are some more examples of how to create a json string in java . details

      Reactions - Positive 0, Negative 1, Others 0

      1. public String createJSONArrayOfObjects() throws JSONException { JSONArray list = new JSONArray()
      2. JSONObject obj = new JSONObject()
      3. obj.put("name", "foo")
      4. obj.put("num", new Integer(100))
      5. obj.put("balance", new Double(1000.21))
      6. obj.put("is_vip", true)
      7. obj.put("nickname", "")
      8. list.put(obj)
      9. obj = new JSONObject()
      10. obj.put("name" , "foo too")
      11. obj.put("num", new Integer(200))
      12. obj.put("balance", new Double(2000.21))
      13. obj.put("is_vip", true)
      14. obj.put("nickname", "")
      15. list.put(obj)
      16. return list.toString()
      17. } public String mixingJSONArrayAndObjects() throws JSONException { JSONArray list1 = new JSONArray()
      18. list1.put("foo")
      19. list1.put(new Integer(100))
      20. list1.put(new Double(1000.21))
      21. JSONArray list2 = new JSONArray()
      22. list2.put(true)
      23. JSONObject obj = new JSONObject()
      24. obj.put("name", "foo")
      25. obj.put("num", new Integer(100))
      26. obj.put("balance", new Double(1000.21))
      27. obj.put("is_vip", true)
      28. obj.put("nickname", "")
      29. obj.put("list1", list1)
      30. obj.put("list2", list2)
      31. return obj.toString()
      32. } public String createJSONArray() throws JSONException { JSONArray list = new JSONArray()
      33. list.put("foo")
      34. list.put(100)
      35. list.put(1000.21)
      36. list.put(true)
      37. return list.toString()
      38. } public void createJSONArrayFromString(String anArray) throws JSONException { JSONArray list = new JSONArray(anArray)
      39. for (int i = 0
      40. i < list.length()
      41. i++) { switch (i) { case 0: System.out.println(i + " " + list.getString(i))
      42. break
      43. case 1: System.out.println(i + " " + list.getInt(i))
      44. break
      45. case 2: System.out.println(i + " " + list.getDouble(i))
      46. break
      47. case 3: System.out.println(i + " " + list.getBoolean(i))
      48. break
      49. } } } public String createObject() throws JSONException { JSONObject obj = new JSONObject()
      50. obj.put("name", "foo")
      51. obj.put("num", new Integer(100))
      52. obj.put("balance", new Double(1000.21))
      53. obj.put("is_vip", true)
      54. obj.put("nickname", "")
      55. return obj.toString()
      56. }

      Negative Reactions
      1. Hello Sir with this i am getting a Http 500 may be problem with servlet,..

    6. Android Java; How can I parse a local JSON file from assets folder into a ListView

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. try{String jsonLocation = AssetJSONFile("formules.json", context)
      2. JSONObject jsonobject = new JSONObject(jsonLocation)
      3. JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules")
      4. for(int i=0
      5. i<jarray.length()
      6. i++){JSONObject jb =(JSONObject) jarray.get(i)
      7. String formula = jb.getString("formule")
      8. String url = jb.getString("url")
      9. }} catch (IOException e) { e.printStackTrace()
      10. } catch (JSONException e) { e.printStackTrace()
      11. }

    7. JSONObjcet with String array toString() output has integer values instead of strings

      Use JSONArray. On Android if we put list as Object Json convert it to String as is so we get 41,14]". details

      Reactions - Positive 2, Negative 2, Others 0

      1. public void test__aaaa(){ try { List<String> test = Arrays.asList("41", "14")
      2. JSONArray array = new JSONArray(test)
      3. JSONObject root = new JSONObject()
      4. JSONObject data = new JSONObject()
      5. root.put("data", data)
      6. data.put("my_array", array)
      7. assertEquals(root.toString(), "{\"data\":{\"my_array\":[\"41\",\"14\"]}}")
      8. } catch (JSONException e1) { } }

      Positive Reactions
      1. Very good job, now the example gives me: {"data":{"my_array":["41","14"]}}.
      2. Oh man, thank for additional info about Android.
      Negative Reactions
      1. So is this Java problem or what?
      2. Wow so this was purely about Android sucking once again.
      Other Reactions
      1. import org.json.JSONException;import org.json.JSONObject; {"data":{"my_array":"[41, 14]"}}.
      2. do you use java-json?
      3. Where does org.json come from?
      4. See my answer, it should work now.
      5. My android sdk min target is 8.
      6. That was the output with your example for me.

    8. How to Convet Java Object in to GeoJSON (Required by d3 Graph)

      GeoJSON is very simple a general JSON library should be all you need. Here's how you could construct a list of Points using the json.org code This will output something like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject featureCollection = new JSONObject()
      2. try { featureCollection.put("type", "featureCollection")
      3. JSONArray featureList = new JSONArray()
      4. // iterate through your list for (ListElement obj : list) { // {"geometry": {"type": "Point", "coordinates": [-94.149, 36.33]} JSONObject point = new JSONObject()
      5. point.put("type", "Point")
      6. // construct a JSONArray from a string
      7. can also use an array or list JSONArray coord = new JSONArray("["+obj.getLon()+","+obj.getLat()+"]")
      8. point.put("coordinates", coord)
      9. JSONObject feature = new JSONObject()
      10. feature.put("geometry", point)
      11. featureList.put(feature)
      12. featureCollection.put("features", featureList)
      13. } } catch (JSONException e) { Log.error("can't save json object: "+e.toString())
      14. } // output the result System.out.println("featureCollection="+featureCollection.toString())

    9. Compare two JSON objects in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HashMap<String, String> inputMap = new HashMap<String, String>()
      2. HashMap<String, String> outputMap = new HashMap<String, String>()
      3. String actualOutput
      4. String actualInput
      5. public void validateJsonObjects(JSONObject input,JSONObject output) throws JSONException{ Object rootInputJava = input
      6. Object rootOutputJava = output
      7. actualOutput = output.toString()
      8. actualInput = input.toString()
      9. arrayOrObject(rootInputJava,rootOutputJava)
      10. }private void arrayOrObject(Object input,Object output) throws JSONException{ if(input instanceof JSONArray){ JSONArray inputArray = (JSONArray) input
      11. JSONArray outputArray = (JSONArray) output
      12. for(int i = 0
      13. i < inputArray.length()
      14. i++) { if(inputArray.get(0) instanceof JSONObject) { JSONObject inputJson = inputArray.getJSONObject(i)
      15. JSONObject outputJson = outputArray.getJSONObject(i)
      16. JSONArray inputArrayNames = inputJson.names()
      17. JSONArray outputArrayNames = outputJson.names()
      18. int X=0
      19. if(inputArrayNames != null && outputArrayNames != null){ if(inputArrayNames.length()<=outputArrayNames.length()) X=outputArrayNames.length()
      20. else X=inputArrayNames.length()
      21. } iterateLoop(X,inputArrayNames,outputArrayNames,inputJson,outputJson)
      22. } } } else if(input instanceof JSONObject){ JSONObject inputJson = (JSONObject) input
      23. JSONObject outputJson = (JSONObject) output
      24. JSONArray inputArrayNames = inputJson.names()
      25. JSONArray outputArrayNames = outputJson.names()
      26. int X=0
      27. if(inputArrayNames != null && outputArrayNames != null){ if(inputArrayNames.length()<=outputArrayNames.length()){ X=outputArrayNames.length()
      28. } else{ X=inputArrayNames.length()
      29. } } iterateLoop(X,inputArrayNames,outputArrayNames,inputJson,outputJson)
      30. } }private void iterateLoop(int X, JSONArray inputArrayNames,JSONArray outputArrayNames, JSONObject inputJson,JSONObject outputJson) throws JSONException { for (int j = 0
      31. j < X
      32. j++) { String inputTag = null
      33. String outputTag = null
      34. if (j >= inputArrayNames.length()) { inputTag = ""
      35. outputMap.put("", "")
      36. } else inputTag = inputArrayNames.getString(j)
      37. if (j >= outputArrayNames.length()) outputTag = ""
      38. else outputTag = outputArrayNames.getString(j)
      39. inputMap.put(inputTag, inputTag)
      40. outputMap.put(outputTag, outputTag)
      41. System.out.println(inputTag)
      42. System.out.println(outputTag)
      43. if (!inputTag.equals(outputTag)) { if (inputMap.containsKey(outputTag)) { System.out.println("******** "+outputTag+" PRESENT *********")
      44. continue
      45. } else if (outputMap.containsKey(inputTag)) { System.out.println("~~~~~~~~~~~ "+inputTag+" PRESENT ~~~~~~~~~~")
      46. continue
      47. } else if (actualOutput.contains(inputTag)) { System.out.println("~~~~~~~~~~~"+inputTag+" PRESENT ~~~~~~~~~~")
      48. continue
      49. } else { System.out.println("The element " + inputTag+ " is not present! JSON mismatch")
      50. fail()
      51. } } if (!inputTag.equals("")) { Object jsonInputLevel2 = inputJson.get(inputTag)
      52. Object jsonOutputLevel2 = outputJson.get(outputTag)
      53. arrayOrObject(jsonInputLevel2, jsonOutputLevel2)
      54. } else { arrayOrObject("", "")
      55. } }}

    10. How to Parse the JSON String Andriod

      You need to create JSONArray from your jsonstring. You have JSONArray inside JSONArray and then JSONObect . details

      Reactions - Positive 0, Negative 0, Others 0

      1. try { JSONArray ja = new JSONArray(buffer.toString())
      2. JSONArray innerJsonArray = ja.getJsonArray(0)
      3. JSONObject object = innerJsonArray.getJSONObject(0)
      4. String title = object.getString("title")
      5. } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString())
      6. }

    11. JSON parsing using JSON-Simple not working

      I was able to get the privacyStatus this way however I cant seem to see anything in their documentation where they show any examples of using a chained get statement like the ones you have. Edit I found this little snippet in some android code I have It will work with the library this is very similar if not the same as the android JSON library . details

      Reactions - Positive 4, Negative 1, Others 0

      1. public static void main(String[] args) { // this is the same JSON string in the OP String jsonString = "{ \"items\": [ { \"id\": \"uy0nALQEAM4\", \"kind\": \"youtube#video\", \"etag\": \"\\\"g-RLCMLrfPIk8n3AxYYPPliWWoo/x3SYRGDdvDsN5QOd7AYVzGOJQlM\\\"\", \"status\": { \"uploadStatus\":\"processed\", \"privacyStatus\": \"public\", \"license\": \"youtube\", \"embeddable\": true, \"publicStatsViewable\": true } } ]}"
      2. JSONObject object = new JSONObject(jsonString)
      3. try { String myValue = (String)getJSONValue("items[0].status.privacyStatus", object)
      4. System.out.println(myValue)
      5. } catch (JSONException ex) { Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex)
      6. }}public static Object getJSONValue(String exp, JSONObject obj) throws JSONException { try { String [] expressions = exp.split("[\\.|\\[|\\]]")
      7. Object currentObject = obj
      8. for(int i=0
      9. i < expressions.length
      10. i++) { if(!expressions[i].trim().equals("")) { System.out.println(expressions[i] + " " + currentObject)
      11. if(currentObject instanceof JSONObject) { Method method = currentObject.getClass().getDeclaredMethod("get", String.class)
      12. currentObject = method.invoke(currentObject, expressions[i])
      13. } else if(currentObject instanceof JSONArray) { Method method = currentObject.getClass().getDeclaredMethod("get", Integer.TYPE)
      14. currentObject = method.invoke(currentObject, Integer.valueOf(expressions[i]))
      15. } else { throw new JSONException("Couldnt access property " + expressions[i] + " from " + currentObject.getClass().getName())
      16. } } } return currentObject
      17. } catch (NoSuchMethodException ex) { throw new JSONException(ex)
      18. } catch (IllegalAccessException ex) { throw new JSONException(ex)
      19. } catch (IllegalArgumentException ex) { throw new JSONException(ex)
      20. } catch (InvocationTargetException ex) { throw new JSONException(ex)
      21. }}

      Positive Reactions
      1. All JSON librarys seem to be kind of bulky and have no great way of accessing nested objects in a clean way.
      2. To do this I would recommend using something like SpEL (spring expression language) or create a small class with some basic java reflection.
      3. If you like I can send something over I have a few snipplets here and there.
      4. I personally prefer GSON its googles support for JSON check out this thread URL_http://stackoverflow.com/questions/338586/a-better-java-json-library .
      Negative Reactions
      1. This does work, but it sure is ugly as hell lol.
      Other Reactions
      1. Maybe I should use another library?
      2. edit: forgot to add URL_http://json.org/java/ .

    12. Finding deeply nested key/value in JSON

      thanks. Based on Stefan Jansen's answer I made some changes and this is what I have now nestedChildren declared globaly and before the children are searched reset to new ArrayList This assumes it is all Arrays witch in my case it is . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private void findAllChild(JSONArray array) throws JSONException { for ( int i=0
      2. i<array.length()
      3. i++ ) { JSONObject json = array.getJSONObject(i)
      4. JSONArray json_array = new JSONArray(json.getString("children"))
      5. nestedChildren.add(json.getString("id"))
      6. if ( json_array.length() > 0 ) { findAllChild(json_array)
      7. } }}

    13. Parse the JSON String efficiently and in a clean way

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public boolean isJSONValid(final String str, final int id) { boolean valid = true
      2. try { final JSONObject obj = new JSONObject(str)
      3. final JSONArray geodata = obj.getJSONArray("lv")
      4. final int n = geodata.length()
      5. for (int i = 0
      6. i < n
      7. ++i) { final JSONObject person = geodata.getJSONObject(i)
      8. JSONObject menu = person.getJSONObject("v")
      9. if(menu.getInt("userId") != id) { valid = false
      10. break
      11. } } } catch (JSONException ex) { valid = false
      12. } return valid
      13. }

    14. Most effecient conversion of ResultSet to JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class ResultSetConverter {
      2. public static JSONArray convert(ResultSet rs) throws SQLException, JSONException {
      3. JSONArray json = new JSONArray()
      4. ResultSetMetaData rsmd = rs.getMetaData()
      5. int numColumns = rsmd.getColumnCount()
      6. while (rs.next()) {
      7. JSONObject obj = new JSONObject()
      8. for (int i = 1 i < numColumns + 1 i++) {
      9. String column_name = rsmd.getColumnName(i)
      10. if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
      11. obj.put(column_name, rs.getArray(column_name))
      12. } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
      13. obj.put(column_name, rs.getLong(column_name))
      14. } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
      15. obj.put(column_name, rs.getFloat(column_name))
      16. } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
      17. obj.put(column_name, rs.getBoolean(column_name))
      18. } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
      19. obj.put(column_name, rs.getBlob(column_name))
      20. } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
      21. obj.put(column_name, rs.getDouble(column_name))
      22. } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
      23. obj.put(column_name, rs.getDouble(column_name))
      24. } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
      25. obj.put(column_name, rs.getInt(column_name))
      26. } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
      27. obj.put(column_name, rs.getNString(column_name))
      28. } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
      29. obj.put(column_name, rs.getString(column_name))
      30. } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
      31. obj.put(column_name, rs.getString(column_name))
      32. } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
      33. obj.put(column_name, rs.getNString(column_name))
      34. } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
      35. obj.put(column_name, rs.getNString(column_name))
      36. } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
      37. obj.put(column_name, rs.getString(column_name))
      38. } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
      39. obj.put(column_name, rs.getByte(column_name))
      40. } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
      41. obj.put(column_name, rs.getShort(column_name))
      42. } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
      43. obj.put(column_name, rs.getDate(column_name))
      44. } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
      45. obj.put(column_name, rs.getTime(column_name))
      46. } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
      47. obj.put(column_name, rs.getTimestamp(column_name))
      48. } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
      49. obj.put(column_name, rs.getBytes(column_name))
      50. } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
      51. obj.put(column_name, rs.getBytes(column_name))
      52. } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
      53. obj.put(column_name, rs.getBinaryStream(column_name))
      54. } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
      55. obj.put(column_name, rs.getBoolean(column_name))
      56. } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
      57. obj.put(column_name, rs.getClob(column_name))
      58. } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
      59. obj.put(column_name, rs.getBigDecimal(column_name))
      60. } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
      61. obj.put(column_name, rs.getBigDecimal(column_name))
      62. } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
      63. obj.put(column_name, rs.getURL(column_name))
      64. } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
      65. obj.put(column_name, rs.getRef(column_name))
      66. } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
      67. obj.put(column_name, rs.getObject(column_name))
      68. // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object. } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) { obj.put(column_name, rs.getObject(column_name))
      69. // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object. } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) { obj.put(column_name, rs.getObject(column_name))
      70. } else {
      71. obj.put(column_name, rs.getString(i))
      72. }
      73. }
      74. json.put(obj)
      75. }
      76. return json
      77. }
      78. }

    15. how to deserialize a json/gson that could be a string , object ,or list

      The same way we can figure out situation when note field is String. In my example code another get operations can also throw jsonExceptions but I think you get the idea. details

      Reactions - Positive 0, Negative 0, Others 0

      1. try { //String jsonString="{\"notes\": {\"note\": [{\"content\": \"Having wisdom teeth removed.\",\"from\": \"employee\" }, {\"content\": \"Get well soon\", \"from\": \"manager\"} ] }}"
      2. //String jsonString="{\"notes\": { \"note\": {\"content\": \"This is a test note.\",\"from\": \"employee\"}}}"
      3. String jsonString="{\"notes\": { \"note\": \"\"}}"
      4. JSONObject jsonObject=new JSONObject(jsonString)
      5. JSONObject jsonObjectNotes=jsonObject.getJSONObject("notes")
      6. try{ JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray("note")
      7. for (int i = 0
      8. i < jsonArrayNote.length()
      9. i++) { JSONObject jsonObject2= jsonArrayNote.getJSONObject(i)
      10. String stringContent=jsonObject2.getString( "content")
      11. String stringFrom= jsonObject2.getString( "from")
      12. Log.e(getClass().getName(), "content="+stringContent +"
      13. from="+stringFrom)
      14. } } catch(JSONException e){ //that means that jsonObjectNotes has no jsonArray with name "notes" and "notes" is jsonObject try{ JSONObject jsonObject3=jsonObjectNotes.getJSONObject("note")
      15. String stringContent=(String) jsonObject3.get( "content")
      16. String stringFrom=(String) jsonObject3.get( "from")
      17. Log.e(getClass().getName(), "content="+stringContent +"
      18. from="+stringFrom)
      19. } catch(JSONException ex){ //that means that jsonObjectNotes has no jsonObject with name "notes" and "notes" is empty String String stringNote=jsonObjectNotes.getString("note")
      20. Log.e(getClass().getName(), "note is string ="+ stringNote)
      21. } } } catch (JSONException e) { e.printStackTrace()
      22. }

      Other Reactions
      1. I sued this concept but with if() blocks using JSONObject.opt to see if there were appropriate values.

    16. Creating a JSON object

      One way I can think of is using the org.json library. I wrote a sample to build part of your request object The output is Another technique would be to build Java objects that resemble your request structure. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String[] args) throws JSONException { JSONObject jsonObject = new JSONObject()
      2. jsonObject.put("method", "SearchBySearchConfiguration")
      3. JSONArray jsonArray = new JSONArray()
      4. JSONObject innerRecord = new JSONObject()
      5. innerRecord.put("SearchCriteria", "%arriva")
      6. innerRecord.put("IsAccountSearch", true)
      7. jsonArray.put(innerRecord)
      8. jsonObject.put("params",jsonArray)
      9. System.out.println("jsonObject :"+jsonObject)
      10. }

    17. Creating a JSON object

      First you need to create classs with following members Usage Serializing Deserializing . See this below example where a JSONArray is returned and then how i am converting it in JSONObject form Jackson is a very efficient to do JSON Parsing See this link Gson is provided by google which is also a good way to handle JSON. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONArray go() throws IOException, JSONException {JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx")
      2. return json
      3. }JSONArray jarr
      4. for(int i=0
      5. i<jarr.length()
      6. i++){JSONObject jobj = jarr.getJSONObject(i)
      7. String mainText = new String()
      8. String provText = new String()
      9. String couText = new String()
      10. try{mainText = jobj.getString("Overview")
      11. System.out.println(mainText)
      12. }catch(Exception ex){}try{JSONObject jProv = jobj.getJSONObject("Provider")
      13. provText = jProv.getString("Name")
      14. System.out.println(provText)
      15. }catch(Exception ex){}try{ JSONObject jCou = jobj.getJSONObject("Counterparty")
      16. couText = jCou.getString("Value")
      17. System.out.println(couText)
      18. }catch(Exception ex){}

    18. Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Loopj { private static final String TAG = "loopj"
      2. private static AsyncHttpClient client = new AsyncHttpClient()
      3. private final PersistentCookieStore myCookieStore
      4. public Loopj(Context context) { myCookieStore = new PersistentCookieStore(context)
      5. client.setCookieStore(myCookieStore)
      6. client.addHeader("Content-type", "application/json")
      7. } public void systemConnect(String uri) throws JSONException { client.post(uri + "/endpoint/system/connect", new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject json) { Log.i("TAG", "Connect success =" + json.toString())
      8. } @Override public void onFailure(Throwable e, String response) { Log.e("TAG", "Connect failure")
      9. } })
      10. } public void userLogin(String uri) throws JSONException { RequestParams params = new RequestParams()
      11. params.put("username", username)
      12. params.put("password", password)
      13. client.post(uri + "/endpoint/user/login", params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray response) { Log.i("TAG", "Login success =" + response.toString())
      14. } @Override public void onFailure(Throwable e, JSONArray json) { Log.e("TAG", "Login failure")
      15. } })
      16. }

    19. JSON array from Django to Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. //parse json datatry{ JSONArray jArray = new JSONArray(result)
      2. for(int i=0
      3. i<jArray.length()
      4. i++){ JSONObject buf = jArray.getJSONObject(i)
      5. JSONObject json_data = buf.getJSONObject("fields")
      6. Brete resultRow = new Brete()
      7. resultRow.contenido = json_data.getString("contenido")
      8. resultRow.fecha = json_data.getString("fecha")
      9. resultRow.correo = json_data.getString("correo")
      10. arrayOfWebData.add(resultRow)
      11. }}catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString())
      12. }

    20. Parsing JSON string in Java

      Apart from that geodata is in fact not a JSONObject but a JSONArray. Here is the fully working and tested corrected code Here's the output . details

      Reactions - Positive 7, Negative 2, Others 0

      1. import org.json.JSONArray
      2. import org.json.JSONException
      3. import org.json.JSONObject
      4. public class ShowActivity {
      5. private static final String JSON_DATA =
      6. "{"
      7. + " \"geodata\": ["
      8. + " {"
      9. + " \"id\": \"1\","
      10. + " \"name\": \"Julie Sherman\","
      11. + " \"gender\" : \"female\","
      12. + " \"latitude\" : \"37.33774833333334\","
      13. + " \"longitude\" : \"-121.88670166666667\""
      14. + " },"
      15. + " {"
      16. + " \"id\": \"2\","
      17. + " \"name\": \"Johnny Depp\","
      18. + " \"gender\" : \"male\","
      19. + " \"latitude\" : \"37.336453\","
      20. + " \"longitude\" : \"-121.884985\""
      21. + " }"
      22. + " ]"
      23. + "}"
      24. public static void main(final String[] argv) throws JSONException {
      25. final JSONObject obj = new JSONObject(JSON_DATA)
      26. final JSONArray geodata = obj.getJSONArray("geodata")
      27. final int n = geodata.length()
      28. for (int i = 0 i < n ++i) {
      29. final JSONObject person = geodata.getJSONObject(i)
      30. System.out.println(person.getInt("id"))
      31. System.out.println(person.getString("name"))
      32. System.out.println(person.getString("gender"))
      33. System.out.println(person.getDouble("latitude"))
      34. System.out.println(person.getDouble("longitude"))
      35. }
      36. }
      37. }

      Positive Reactions
      1. @Nevzz03 I have posted fully working code now.
      2. Thanks a lot veer.
      3. at org.json.JSONObject.getJSONObject(JSONObject.java:596) at com.niharika.testing.JsonTest.main(JsonTest.java:31) Any thoughts will be appreciated.
      4. Glad I could help :-) Note you won't need the json.jar when deploying via Android.
      5. Let me know how it works out for you.
      6. Really appreciate all your help!
      7. Thanks veer.
      Negative Reactions
      1. And when I ran my project, I got exception as- Exception in thread "main" org.json.JSONException: JSONObject["geodata"] is not a JSONObject.
      2. @Nevzz03 no problem dude!
      Other Reactions
      1. I downloaded the jar also, imported into our project too.
      2. !.
      3. I opened that link but I couldn't find the jar file to download.
      4. Can you point me to exact location from where I can download it.
      5. @Nevzz03 try [here]( URL_http://repo1.maven.org/maven2/org/json/json/20090211/json - 20090211.jar).
      6. I did as per your suggestion.

    21. How to find another element in a jArray if I know a string contained in it?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. try { //JSONArray jArray = new JSONArray()
      2. JSONObject item
      3. boolean found = false
      4. int length = jArray.length()
      5. String key = "message"
      6. String orphan = "message2"
      7. // Let's find where you belong for(int index = 0
      8. index < length
      9. index++) { item = jArray.getJSONObject(index)
      10. if(item.getString(key).equals(orphan)) { found = true
      11. break
      12. } } if(found) { // item references the JSONObject that you want } else { // No match found }}catch(JSONException e) { // Try to handle the error gracefully}

    22. Transform JSONArray into array of JSONObject

      Still looking for build in function or concrete implementation on this. Output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String inputStr = "[[\"title\",\"details\"],[\"abc\",\"xyz\"],[\"abc2\",\"xyz2\"]]"
      2. try { JSONArray inputArray = new JSONArray(inputStr)
      3. JSONArray outputArray = new JSONArray()
      4. for (int i = 0
      5. i < inputArray.length()
      6. i++) { JSONArray inArr = inputArray.getJSONArray(i)
      7. for (int j = 0
      8. j < inArr.length()
      9. j++) { if (i != 0) { outputArray.put(new JSONObject().put( inputArray.getJSONArray(0).getString(j), inArr.get(j)))
      10. } } } System.out.println("outputArray = " + outputArray.toString())
      11. } catch (JSONException jse) { System.out.println("jse = " + jse.toString())
      12. }

    23. JSON parsing using Jettison

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String[] args) throws Exception { String s ="[{\"appUsage\":{\"appName\":\"ANDROID\",\"totalUsers\":\"0\"}},{\"appUsage\":{\"appName\":\"IOS\",\"totalUsers\":\"4\"}}]"
      2. JSONArray arr = new JSONArray(s)
      3. List<MiAppUsage> list = unmarshal(MiAppUsage.class, arr)
      4. for(MiAppUsage miAppUsage : list) { System.out.println(miAppUsage.appName + ": " + miAppUsage.totalUsers)
      5. }}public static <T> List<T> unmarshal(Class<T> cls, JSONArray arr) throws JSONException, XMLStreamException, JAXBException { List<T> list = new ArrayList<T>()
      6. for (int i = 0
      7. i < arr.length()
      8. i++) { list.add(unmarshal(cls, arr.getJSONObject(i)))
      9. } return list
      10. }public static <T> T unmarshal(Class<T> cls, JSONObject obj) throws JSONException, XMLStreamException, JAXBException { JAXBContext jc = JAXBContext.newInstance(cls)
      11. Configuration config = new Configuration()
      12. MappedNamespaceConvention con = new MappedNamespaceConvention(config)
      13. XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con)
      14. Unmarshaller unmarshaller = jc.createUnmarshaller()
      15. return cls.cast(unmarshaller.unmarshal(xmlStreamReader))
      16. }

    24. How to get and set JSONObject , JSONArray in J2ME

      That a great method given Thanks. In the below link implementation-for-array-object json-implementation-for-array-object/ they have explained how a JSONArray is used Where Threaddata is a class defined for a JSONObject and it has been made in array object check out the link . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void fromJSON(String jsonString) { try { JSONObject json = new JSONObject(jsonString)
      2. setApi_status(json.getString("api_status"))
      3. JSONArray jsonArray = json.getJSONArray("threads")
      4. int total = jsonArray.length()
      5. ThreadData[] threads = new ThreadData[total]
      6. for (int i=0
      7. i<total
      8. i++) { String threadsJSON = jsonArray.getString(i)
      9. threads[i] = new ThreadData()
      10. threads[i].fromJSON(threadsJSON)
      11. } setThreads(threads)
      12. } catch (JSONException ex) { ex.printStackTrace()
      13. } } public String toJSON() { JSONObject inner = new JSONObject()
      14. try { inner.put("api_status", getApi_status())
      15. JSONArray jsonArray = new JSONArray()
      16. ThreadData[] threads = getThreads()
      17. for (int i=0
      18. i<threads.length
      19. i++) { jsonArray.put(threads[i].toJSON())
      20. } inner.put("threads", jsonArray)
      21. } catch (JSONException ex) { ex.printStackTrace()
      22. } return inner.toString()
      23. }

    25. How to get and set JSONObject , JSONArray in J2ME

      App Loader In this class I created getters and setters for the String type of objects and then created JsonObject to create a JSON object to create a JSON object and then vice versa as per functions and User Data class i found a better link for this question object array-object/ . ple.html Check-this-link-for-different-JSON-Data-Set-Sample One Example for your Understanding JSON String Nested with Arrays To check its valid or not check-this-link-(JSON Validator) To check JSON-Viewer So Here is code take look You can use your same concept to set get data like above you did. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String json = "{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\"" + ",\"ppu\":0.55,\"batters\":{\"batter\":[" + "{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\"," + "\"type\":\"Chocolate\"},{\"id\":\"1003\"," + "\"type\": \"Blueberry\" },{ \"id\": \"1004\", " + "\"type\": \"Devil's Food\" } ] }," + " \"topping\":[" + "{ \"id\": \"5001\", \"type\": \"None\" }," + "{ \"id\": \"5002\", \"type\": \"Glazed\" }," + "{ \"id\": \"5005\", \"type\": \"Sugar\" }," + "{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" }," + " { \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" }," + "{ \"id\": \"5003\", \"type\": \"Chocolate\" }," + "{ \"id\": \"5004\", \"type\": \"Maple\" }]}"
      2. try { JSONObject root = new JSONObject(json)
      3. String id = root.getString("id")
      4. double dd = root.getDouble("ppu")
      5. System.out.println(""+id)
      6. System.out.println(""+dd)
      7. JSONObject batters=new JSONObject(root.getString("batters"))
      8. JSONArray batter=new JSONArray(batters.getString("batter"))
      9. for(int j=0
      10. j<batter.length()
      11. j++){ JSONObject navgt_batter=new JSONObject(batter.getString(j))
      12. String id_batter= navgt_batter.getString("id")
      13. String type_batter=navgt_batter.getString("type")
      14. System.out.println(""+id+" "+type_batter)
      15. } JSONArray topping=root.getJSONArray("topping")
      16. for(int k=0
      17. k<topping.length()
      18. k++){ JSONObject navgt_batter=new JSONObject(topping.getString(k))
      19. String id_top =navgt_batter.getString("id")
      20. String type_top=navgt_batter.getString("type")
      21. System.out.println(""+id_top+" "+type_top)
      22. } } catch (JSONException ex) { ex.printStackTrace()
      23. }

      Positive Reactions
      1. That a great method given Thanks.

    26. Java JSON serialization - best practice

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONObject dump() throws JSONException { JSONObject result = new JSONObject()
      2. JSONArray a = new JSONArray()
      3. for(T i : items){ a.put(i.dump())
      4. // inside this i.dump(), store "class-name" } result.put("items", a)
      5. return result
      6. }public void load(JSONObject obj) throws JSONException { JSONArray arrayItems = obj.getJSONArray("items")
      7. for (int i = 0
      8. i < arrayItems.length()
      9. i++) { JSONObject item = arrayItems.getJSONObject(i)
      10. String className = item.getString("class-name")
      11. try { Class<?> clazzy = Class.forName(className)
      12. T newItem = (T) clazzy.newInstance()
      13. newItem.load(obj)
      14. items.add(newItem)
      15. } catch (InstantiationException e) { // whatever } catch (IllegalAccessException e) { // whatever } catch (ClassNotFoundException e) { // whatever } }

    27. Java JSON serialization - best practice

      Though you have chosen to use Gson a good decision). Here is the quick snippet for u for ur problem I have not tested it but it should work I believe. details

      Reactions - Positive 1, Negative 1, Others 0

      1. public void load(JSONObject result) throws JSONException{ JSONArray a = (JSONArray) result.get("items")
      2. for (int i = 0
      3. i < a.length()
      4. i++) { T t = (T)a.get(i)
      5. items.add(t)
      6. }}

      Positive Reactions
      1. I doubt that works.
      Negative Reactions
      1. Code is missing the step to data bind from JSONObject to actual type T; and for that one also needs class argument (or name to find class definition).
      Other Reactions
      1. You can't just arbitrarily cast types of json.org lib to POJOs.

    28. android how to convert the json object to json array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jArrayObject = new JSONArray()
      2. jArrayObject.put(getJsonObject())
      3. private static JSONObject getJsonObject() throws JSONException { JSONObject jObject = new JSONObject()
      4. //put value jObject here..}

    29. Returning JSON response from Servlet to Javascript/JSP page

      I should have been building a JSONArray of JSONObjects and then add the array to a final Addresses JSONObject. Observe the following This worked and returned valid and parse-able JSON. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject json = new JSONObject()
      2. JSONArray addresses = new JSONArray()
      3. JSONObject address
      4. try{ int count = 15
      5. for (int i=0
      6. i<count
      7. i++) { address = new JSONObject()
      8. address.put("CustomerName" , "Decepticons" + i)
      9. address.put("AccountId" , "1999" + i)
      10. address.put("SiteId" , "1888" + i)
      11. address.put("Number" , "7" + i)
      12. address.put("Building" , "StarScream Skyscraper" + i)
      13. address.put("Street" , "Devestator Avenue" + i)
      14. address.put("City" , "Megatron City" + i)
      15. address.put("ZipCode" , "ZZ00 XX1" + i)
      16. address.put("Country" , "CyberTron" + i)
      17. addresses.add(address)
      18. } json.put("Addresses", addresses)
      19. }catch (JSONException jse){ }response.setContentType("application/json")
      20. response.getWriter().write(json.toString())

      Positive Reactions
      1. Hi majestica - glad it is solved.
      2. please mark this answer or the other as "accepted".

    30. Java JSON pulling value from selected name in JSONObject from JSONArray

      e.g. to retrieve filename from above json string . details

      Reactions - Positive 2, Negative 0, Others 0

      1. try { String jsonString = new String("{\"filelist\": [{ \"1\": { \"filename\": \"sample.mp3\", \"baseurl\": \"http://www.hostchick.com/deemster/\" }}]}")
      2. JSONObject jObj = new JSONObject(jsonString)
      3. JSONArray jArr
      4. jArr = jObj.getJSONArray("filelist")
      5. JSONObject jobj = jArr.getJSONObject(0)
      6. String filename = jobj.getJSONObject("1").getString("filename")
      7. Toast.makeText(this, filename, Toast.LENGTH_SHORT).show()
      8. } catch (JSONException e) { e.printStackTrace()
      9. }

      Positive Reactions
      1. Thank you as well.
      2. Your code works too.
      Other Reactions
      1. :).

    31. Java JSON pulling value from selected name in JSONObject from JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jObj
      2. try { jObj = new JSONObject(jsonString)
      3. JSONArray jArr = jObj.getJSONArray("filelist")
      4. JSONObject jObj2 = jArr.getJSONObject(0)
      5. textView1.setText(jObj2.getJSONObject("1").getString("filename"))
      6. } catch (JSONException e) { e.printStackTrace()
      7. }

    32. Java JSON pulling value from selected name in JSONObject from JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jObj
      2. try { jObj = new JSONObject(jsonString)
      3. JSONArray jArr = jObj.getJSONArray("filelist")
      4. JSONObject jObj2 = jArr.getJSONObject(0)
      5. textView1.setText(jObj2.getString("filename"))
      6. } catch (JSONException e) { e.printStackTrace()
      7. }

    33. Using JSON with MongoDB?

      OK it seems there is no interoperability so I rolled my own. Busywork to get around the type system . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Util {
      2. public static DBObject encode(JSONArray a) {
      3. BasicDBList result = new BasicDBList()
      4. try {
      5. for (int i = 0 i < a.length() ++i) {
      6. Object o = a.get(i)
      7. if (o instanceof JSONObject) {
      8. result.add(encode((JSONObject) o))
      9. } else if (o instanceof JSONArray) {
      10. result.add(encode((JSONArray) o))
      11. } else {
      12. result.add(o)
      13. }
      14. }
      15. return result
      16. } catch (JSONException je) {
      17. return null
      18. }
      19. }
      20. public static DBObject encode(JSONObject o) {
      21. BasicDBObject result = new BasicDBObject()
      22. try {
      23. Iterator i = o.keys()
      24. while (i.hasNext()) {
      25. String k = (String) i.next()
      26. Object v = o.get(k)
      27. if (v instanceof JSONArray) {
      28. result.put(k, encode((JSONArray) v))
      29. } else if (v instanceof JSONObject) {
      30. result.put(k, encode((JSONObject) v))
      31. } else {
      32. result.put(k, v)
      33. }
      34. }
      35. return result
      36. } catch (JSONException je) {
      37. return null
      38. }
      39. }
      40. }

  2. Converting the Database details to JSON object

    Your key would be column name and value would be content. For the records array you need to build it while iterating table columns.Combining above code with building records array would be something like this . .. details

    1. String[] group = {"titleField","titleIDMap","titleId","titleStartDate","titleEndDate","languageId"}
    2. List<String> recordGroup = Arrays.asList(group)
    3. Map<Object, JSONArray> records = new HashMap<Object,JSONArray>()
    4. List<Map<String,Object>> objList = dao.getStatus()
    5. JSONObject jsonData = new JSONObject()
    6. if(objList!=null && objList.size()>10000){ for(Map<String,Object> row : objList) { int columnCount = 0
    7. Iterator<String> keyList = row.keySet().iterator()
    8. while(keyList.hasNext()){ String key = keyList.next()
    9. if(recordGroup.contains(key)){ Object recordId = row.get("recordId")
    10. JSONArray recordArray = new JSONArray()
    11. if(records.containsKey(recordId)){ recordArray = records.get(recordId)
    12. JSONObject jsonObj = null
    13. if(columnCount >= recordGroup.size()){ jsonObj = new JSONObject()
    14. recordarray.add(jsonObj)
    15. columnCount = 0
    16. } else { jsonObj = (JSONObject) recordArray.get(recordArray.size()-1)
    17. } jsonObj.put(key, row.get(key))
    18. columnCount++
    19. } else { JSONObject jsonObj = new JSONObject()
    20. jsonObj.put(key, row.get(key))
    21. recordArray.add(jsonObj)
    22. records.put(recordId, recordArray)
    23. } jsonData.put("records", records.get(recordId))
    24. } else { jsonData.put(key, row.get(key))
    25. } } } }

    Other Reactions
    1. what abt records array?

    • See Also (110)
    1. Using Json to access a specific attribute

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jObj = new JSONObject(result)
      2. JSONArray rows = jObj.getJSONArray("rows")
      3. for(int i = 0
      4. i < rows.length
      5. i++){ JSONObject obj = rows.getJSONObject(i)
      6. JSONArray elements = jObj.getJSONArray("elements")
      7. for(int j = 0
      8. j < elements.length
      9. j++){ JSONObject Jobj = elements.getJSONObject(j)
      10. JSONObject distance = Jobj.getJSONObject("distance")
      11. int distance_value = distance.getInteger("value")
      12. JSONObject duration = Jobj.getJSONObject("duration")
      13. int duration_value = duration.getInteger("value")
      14. }}

    2. java iterate over JSONObject?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray list =result.getJSONArray(arrayName)
      2. for (int i = 0
      3. i < list.length()
      4. ++i) { JSONObject item = list.getJSONObject(i)
      5. }

    3. Android JSON Parsing And Conversion

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jso3 = new JSONObject(output)
      2. String name = jso3.getString("Nombre")
      3. String surname = jso3.getString("Apellidos")
      4. int date = jso3.getInt("Ao_nacimiento")
      5. JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos")
      6. for(int i=0
      7. i<menuObject.length
      8. i++){ System.out.println(menuObject.getString(i))
      9. }

    4. Android JSON Parsing And Conversion

      Try this. Your response like below To parse the JSON use below code . details

      Reactions - Positive 2, Negative 0, Others 0

      1. { ==> JSONObject "Ao_nacimiento": 1990, ==> String from JSONObject "Nombres_Hijos": [ ==> JSONArray "Blur", ==> Directly from JSONArray "Clur" ], "Apellidos": "Garcia", "Nombre": "Miguel"}

      Positive Reactions
      1. Thank you but I'm getting errors in all the "get" functions: "The method getString(int) in the type JSONArray is not applicable for the arguments (String)", "The method getInt(int) in the type JSONArray is not applicable for the arguments (String)", "The method getJSONArray(int) in the type JSONArray is not applicable for the arguments (String)", and in the .toString function "The method toString(int) in the type JSONArray is not applicable for the arguments (String)".
      2. @user3082271 if your response like my ans JSON then ans is correct.

    5. Read json from string in java

      Took this snippet directly from the decoding-examples page link above. JSONObject is a java.util.Map and JSONArray is a java.util.List so you can access them with standard operations of Map or List . details

      Reactions - Positive 0, Negative 0, Others 0

      1. System.out.println("=======decode=======")
      2. String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"
      3. Object obj=JSONValue.parse(s)
      4. JSONArray array=(JSONArray)obj
      5. System.out.println("======the 2nd element of array======")
      6. System.out.println(array.get(1))
      7. System.out.println()
      8. JSONObject obj2=(JSONObject)array.get(1)
      9. System.out.println("======field \"1\"==========")
      10. System.out.println(obj2.get("1"))
      11. s="{}"
      12. obj=JSONValue.parse(s)
      13. System.out.println(obj)
      14. s="[5,]"
      15. obj=JSONValue.parse(s)
      16. System.out.println(obj)
      17. s="[5,,2]"
      18. obj=JSONValue.parse(s)
      19. System.out.println(obj)

    6. Convert JSON Result to Java Array

      Some of the heavily used frameworks are json-lib/jackson/gson . try this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jObject= new JSONObject(output)
      2. JSONArray menuObject = new JSONArray(jObject.getString("21"))
      3. String sku,entity_id
      4. for (int i = 0
      5. i<menuObject.length()
      6. i++) { entity_id=menuObject.getJSONObject(i).getString("entity_id")
      7. sku= menuObject.getJSONObject(i).getString("entity_id")
      8. }

      Other Reactions
      1. i cannot add the output in jsonobject.

    7. Parsing table html with Jsoup

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Document doc = Jsoup.parse(url)
      2. JSONObject jsonObject = new JSONObject()
      3. JSONArray list = new JSONArray()
      4. Element elementsByTag = doc.getElementsByTag("table").get(1)
      5. Elements rows = elementsByTag.getElementsByTag("tr")
      6. for(Element row : rows) { String Test = row.getElementsByTag("td").get(1).text()
      7. String Result = row.getElementsByTag("td").get(2).text()
      8. String Credit = row.getElementsByTag("td").get(3).text()
      9. jsonObject.put("Test", Test)
      10. jsonObject.put("Result", Result)
      11. jsonObject.put("Credit", Credit)
      12. }

    8. Create JsonArray without key value

      What your are trying to do is just to fill an array with primitive variables to achieve that you have to change your code like this . Sample Code You can use this to put an array without key. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj = new JSONObject()
      2. JSONArray list = new JSONArray()
      3. list.add("msg 1")
      4. list.add("msg 2")
      5. list.add("msg 3")
      6. obj.put("", list)

      Other Reactions
      1. i will just put lib file name which you can add in project.

    9. Create JsonArray without key value

      It should looks like I have tried it with empty key value Result looks bad . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject obj = new JsonObject()
      2. JsonArray array = new JsonArray()
      3. array.add(new JsonPrimitive("one"))
      4. array.add(new JsonPrimitive("two"))
      5. array.add(new JsonPrimitive("three"))
      6. obj.add("main", array)

    10. Error Parsing JSON Data - Asynchronous Task

      I cannot use your code because the url will not work from my side . Anyways here is my code . details

      Reactions - Positive 2, Negative 0, Others 0

      1. package com.example.test
      2. import java.io.InputStream
      3. import org.json.JSONArray
      4. import org.json.JSONException
      5. import org.json.JSONObject
      6. import android.app.Activity
      7. import android.content.Intent
      8. import android.os.Bundle
      9. import android.view.Menu
      10. public class MainActivity extends Activity { static InputStream is = null
      11. static JSONObject jObj = null
      12. String jsonString
      13. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
      14. setContentView(R.layout.activity_main)
      15. // Making HTTP request // String url = "http://api.worldbank.org/countries/ir?format=json"
      16. String url = "http://10.0.2.2/andApp/artikel.php"
      17. JSONParser jParser = new JSONParser()
      18. // Getting JSON from URL // JSONArray json = jParser.getJSONFromUrl(url)
      19. // JSONObject json = jParser.getJSONFromUrl1(url)
      20. // JSONObject json = null
      21. JSONArray json = null
      22. try { InputStream is = getAssets().open("json1.json")
      23. int size = is.available()
      24. byte[] buffer = new byte[size]
      25. is.read(buffer)
      26. is.close()
      27. jsonString = new String(buffer, "UTF-8")
      28. // json = new JSONObject(jsonString)
      29. json = new JSONArray(jsonString)
      30. } catch (Exception e) { e.printStackTrace()
      31. } try { JSONArray json2 = json
      32. // .getJSONArray("artikel")
      33. for (int i = 0
      34. i < json2.length()
      35. i++) { JSONObject c = json2.getJSONObject(i)
      36. // Storing JSON item in a Variable String name = c.optString("KEY_ROWID", "")
      37. String capitalCity = c.optString("KEY_NAME", "")
      38. String score = c.optString("KEY_SCORE", "")
      39. String date = c.optString("KEY_DATE", "")
      40. } } catch (JSONException e) { e.printStackTrace()
      41. } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu
      42. this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu)
      43. return true
      44. }}

      Positive Reactions
      1. Thanks for any help.
      2. thanks dude, I will try this later tonight, or tomorrow, 6pm Friday Local time here :).
      Other Reactions
      1. I get an error at JSONParser jParser new JSONParser(); I tried to find an example of this class at URL_http://stackoverflow.com/questions/13202304 /jsonparser-cannot-be-resolved-to-a-type Should I be following that?
      2. Or possibly this: URL_http://www.androidhive.info/2012/05/how-to-connect-android - with-php-mysql/ .
      3. You should debug your code.
      4. Whichever method you are using, DEBUG your code line by line and see if it is working.
      5. Dude listen, that is a class for parsing json from url.

    11. How to parse from this JSONString?

      I edit your post and then I accept it. this may help you just pass String response to loadAmountFrom(String method . details

      Reactions - Positive 0, Negative 0, Others 0

      1. private ArrayList<String> arrayList = new ArrayList<String>()
      2. public void loadAmountFrom(String jsonArrayString) { try { JSONArray jsonArray = new JSONArray(jsonArrayString)
      3. loadAmountFromJsonArray(jsonArray)
      4. } catch (Exception e) { // TODO: handle exception }}private void loadAmountFromJsonArray(JSONArray jsonArray) { try { for (int i = 0
      5. i < jsonArray.length()
      6. i++) { Object object = jsonArray.get(i)
      7. if (object instanceof JSONArray) { loadAmountFromJsonArray(jsonArray)
      8. } else if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object
      9. loadAmount(jsonObject)
      10. } } } catch (Exception e) { // TODO: handle exception }}private void loadAmount(JSONObject jsonObject) { try { Iterator<String> iterator = jsonObject.keys()
      11. while(iterator.hasNext()) { String key = (String) iterator.next()
      12. if(key.equals("amount")) { Object object = jsonObject.get(key)
      13. arrayList.add(object.toString())
      14. } else { Object object = jsonObject.get(key)
      15. if(object instanceof JSONArray) { loadAmountFromJsonArray((JSONArray) object)
      16. } else if(object instanceof JSONObject) { loadAmount((JSONObject) object)
      17. } } } } catch (Exception e) { // TODO: handle exception }}

    12. How to create a Restful web-service of JSON data in java,tomcat,eclipse

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONObject getValues(){ JSONObject jsonobj=new JSONObject()
      2. jsonobj.put("name","Ersin")
      3. jsonobj.put("surname","etinkaya")
      4. jsonobj.put("age","25")
      5. JSONArray obj = new JSONArray()
      6. HashMap rows=new HashMap()
      7. rows.put("city","Bursa")
      8. rows.put("country","Trkiye")
      9. rows.put("zipCode","33444")
      10. obj.put(rows)
      11. jsonobj.put("address", obj)
      12. JSONArray phobj = new JSONArray()
      13. phobj.put("234234242")
      14. phobj.put("345345354")
      15. jsonobj.put("phones", phobj)
      16. System.out.println(jsonobj.toString())
      17. return jsonobj.toString()
      18. }

    13. Exception when handling JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject cannot be converted to JSONArray.

    14. Android Java - Get JSON Value

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonData = jObj.getJSONArray("allergens")
      2. for(int i=0
      3. i<jsonData.length()
      4. i++){ JSONObject jb = (JSONObject) jsonData.get(i)
      5. String allergenname = jb.getString("allergen_name")
      6. }

    15. How to Create a Restful service for a Huge JSON data using Java eclipse Tomcat7.0

      There are a lots of good stuffs available in Google related with REST web-service. Anyway Take a look at this stuff Building-a-Simple-RESTful-Web-Service-to-produce-JSON-using-Jersey Developing-REST-Web-Services-in-Eclipse For creating a JSON see this example Say you want to create a JSON as shown below The java code for creating the above JSON is as given below . details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONArray obj = new JSONArray()
      2. JSONObject jsonobj=new JSONObject()
      3. HashMap rows=new HashMap()
      4. rows.put("tableno","123")
      5. rows.put("status","active")
      6. rows.put("section","pub")
      7. rows.put("custid","12")
      8. obj.put(rows)
      9. jsonobj.put("hoteltables", obj)
      10. obj = new JSONArray()
      11. rows=new HashMap()
      12. rows.put("itemid","12")
      13. rows.put("item","ABC")
      14. rows.put("status","available")
      15. rows.put("section","pub")
      16. rows.put("imagename","XYZ")
      17. obj.put(rows)
      18. jsonobj.put("mainiteam", obj)
      19. obj = new JSONArray()
      20. rows=new HashMap()
      21. rows.put("baseitem","148")
      22. rows.put("item","HIJ")
      23. rows.put("rate","123")
      24. rows.put("section","pub")
      25. rows.put("imagename","pic.png")
      26. obj.put(rows)
      27. jsonobj.put("subitem", obj)
      28. System.out.println(jsonobj.toString())

      Positive Reactions
      1. Thanks for responce,..
      2. Thank You sir,....
      3. Thanks for Responce sir,... i will try with first one ,.
      Other Reactions
      1. But it has to follow on JSON RESTFUL eclipse tomcat,...
      2. is there any example for Json Data for Big files if there give me links ,...
      3. see my updated answer.......
      4. its ok sir,... it helped me,..
      5. Hi Nidhishkrishnan sir,.. in the above code can you how to use this with example which is mentioned on URL_http://www.jeeconsultant.com/sites/jeeconsultant .nsf/docs/Building%20a%20Simple%20RESTful%20Web%20Service%20to%20produce%20JSO N%20using%20Jersey can you tell me,..
      6. since java has json libraries which can be parse JSON easily better than XML.
      7. what about the first example in my answer which I've given you......
      8. that should be defined within the getAllControls() method....
      9. it doesn't matter how big your JSON data is.
      10. by second one is My eclipse I am using Eclipse and tomcat,.. its ok i will go with first one i have a big JSON data do on this,.. so i am thinking is there any other way with java JSON Tomcat,.. Eclipse J2ee,...

    16. Access to the values ​​in a multi-level JSON-structure

      MarkKorzhov and your json having error SyntaxError Unexpected token o. Here is the idea Let me know if it does not compile otherwise should work. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject parent = (JSONObject) lev1.get("parent")
      2. JSONArray child1 = (JSONArray) parent.get("child1")
      3. // same for child2for (Object elem : child1) { System.out.prinlnt("date = " + ((JSONObject) elem).get("date"))
      4. System.out.prinlnt("time = " + ((JSONObject) elem).get("time"))
      5. }

      Positive Reactions
      1. It works!
      2. Thank you!.

    17. JSON Parsing using minimal-json and Gson

      Unless your objects support a get all elements of this type operation and I don't think that would be a minimal implementation. Thanks a lot HotLicks. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String s = response.toString()
      2. JsonArray json = JsonArray.readFrom(s)
      3. for (int i = 0
      4. i < json.size()
      5. i++) { JsonObject show = json.get(i).asObject()
      6. int episode = show.get("episode").asInt()
      7. String time = show.get("first_aired_iso").asString()
      8. System.out.println("Episode " + episode + " - " + time)
      9. }

      Positive Reactions
      1. Yeah, I did that, but forgot to mention it in the comment.Thanks again!
      Other Reactions
      1. Close.
      2. (Though "count" may be "size" or some other name -- I don't know your toolset.
      3. ).
      4. :).
      5. Change get(0) to get(i).
      6. And make your loop be int i 0; i < json.count(); i++.

    18. Issues storing db results in JSONObject

      Feel free to ask if you don't understand any part. Also I would recommend to read about buiding JSON objects. details

      Reactions - Positive 6, Negative 3, Others 0

      1. public static JSONObject fetchPersonCarInfo(String person) throws SQLException { JSONObject personCarInfoObj = new JSONObject()
      2. Connection connection = null
      3. PreparedStatement statement = null
      4. ResultSet rs = null
      5. try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password")
      6. statement = connection.prepareStatement("SELECT personId, carId, purchaseDate FROM person WHERE person = ?")
      7. statement.setString(1, person)
      8. rs = statement.executeQuery()
      9. JSONArray carsArray = null
      10. while (rs.next()) { // lookup if we have an entry for personId already in personCarInfoObj if (personCarInfoObj.containsKey(rs.getString("personId"))) { // build a new object for car info JSONObject personCarObj = new JSONObject()
      11. carsArray = (JSONArray) personCarInfoObj.get(rs.getString("personId"))
      12. personCarObj.put("deviceId", (new String(rs.getString("carId"))))
      13. personCarObj.put("deviceCheckinTime", new Date(rs.getTimestamp("purchaseDate").getTime()))
      14. //not sure how to get timestamp column // this will append new car info object to the array with key rs.getString("personId")) carsArray.add(personCarObj)
      15. personCarInfoObj.put(rs.getString("personId"), carsArray)
      16. } else { carsArray = new JSONArray()
      17. JSONObject personCarObj = new JSONObject()
      18. personCarObj.put("deviceId", (new String(rs.getString("carId"))))
      19. personCarObj.put("deviceCheckinTime", new Date(rs.getTimestamp("purchaseDate").getTime()))
      20. //not sure how to get timestamp column carsArray.add(personCarObj)
      21. // store all the cars purchased against that personId in personCarInfoObj personCarInfoObj.put(new String(rs.getString("personId")), carsArray)
      22. } } } finally { statement.close()
      23. connection.close()
      24. } return personCarInfoObj
      25. }

      Positive Reactions
      1. Thanks so much buddy.
      2. It will work with org.json.simple api as well.
      3. Still no luck :( Doesn't print all the carIds, and their purchase date.
      4. Please have a look.
      5. Thanks so much mohan.
      6. Glad I was of service :).
      Negative Reactions
      1. Eclipse is throwing an error on this line too.
      2. I see it in the API, but eclipse shows an error.
      3. Also, this is incorrect - new Date(rs.getTimestamp("purchaseDate")).getTime()).
      Other Reactions
      1. - personCarInfoObj.put(rs.getString("personId"), personCarObj);.
      2. I tried what you suggested.
      3. which api are you referring to?
      4. I am using import org.json.simple.JSONObject, and I don't have JSONObject.append.
      5. I am referring [this]( URL_http://www.json.org/javadoc/org/json/JSONObject.html ) API.
      6. Let me give it a try.
      7. will a put work in place of append?
      8. I have made the edits.
      9. purchaseDate is of datatype timestamp.
      10. What is column type and format of data stored in "purchaseDate" column?
      11. It worked.
      12. Does it work for you?
      13. Only prints 2 records :(.

    19. Store multiple JSON documents (in row arrays format with nested JSON key-value objects) in MongoDB

      So you have to first convert your string to Object and then insert it. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. String JSONstr = "[1, \"A\", \"B\", 10,{\"key\":\"val\"}]"
      2. JSONArray jsonArray = new JSONArray(JSONstr)
      3. JSONObject jsonObject = new JSONObject()
      4. jsonObject.put("data", jsonArray)
      5. DBObject bson = (DBObject) JSON.parse(jsonObject.toString())
      6. WriteResult insert = newColl.insert(bson)

      Positive Reactions
      1. Thanks.
      Other Reactions
      1. @user1264304 You can download the jar from [here]( URL_http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm) .
      2. I can't find it in JAVA driver API of MongoDB.
      3. But, what is JSONArray, JSONObject?

    20. Converting JSON to Java

      What's wrong with the standard stuff. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(someJsonString)
      2. JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray")
      3. String value = jsonArray.optJSONObject(i).getString("someJsonValue")

    21. how to retrieve JSON object from the JSON array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject transactiondata = (JsonObject)Offer.get("transData")
      2. JsonObject ticketdata = (JsonObject)transactiondata.get("tickets")
      3. JsonObject offerData = (JsonObject)Offer.get("offerData")
      4. JsonObject offerData1 = (JsonObject)offerData.get("offerconfig")
      5. JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails")
      6. double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString())
      7. System.out.println("ticketPrice:"+ticketPrice)

    22. Removing the end [ and ] from php Json result for Android Java code

      you are the man. Solution 1 Java How about a helper method like this Then you could use it like Note I haven't tested this code so you may need to make some changes Alternate solution PHP It's been awhile since I've worked with PHP but you might be able to leave your Java code intact and change your PHP int the while-loop body to . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonArray = new JSONArray(result)
      2. // note the *JSONArray* vs your *JSONObject*n870 = getProp("A70_870", jsonArray)
      3. n871 = getProp("A70_871", jsonArray)
      4. ...

    23. Removing the end [ and ] from php Json result for Android Java code

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private int getProp(String name, JSONArray arr) throws Exception { for (int i = 0
      2. i < arr.length()
      3. ++i) { JSONObject obj = arr.getJSONObject(i)
      4. if (obj.has(name)) return obj.getInt(name)
      5. } throw new Exception("Key not found")
      6. }

    24. How to gather data from a JSON URL and display it

      I had read the values from file but you can read from URL the extracting process code is present inside extractJson method. You could use ArrayList to store the values which will be available inside for loop**. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String [] args){ try { FileInputStream fis=new FileInputStream("testjson.json")
      2. int b=0
      3. String val=""
      4. while((b=fis.read())!=-1) { val=val+(char)b
      5. } extractJson(val)
      6. } catch(Exception e) { e.printStackTrace()
      7. }}public static void extractJson(String json){ try { JSONObject jobject=new JSONObject(json)
      8. System.out.println("Json object Length: "+jobject.length())
      9. System.out.println("Status: "+jobject.getString("status"))
      10. JSONArray jarray=new JSONArray(jobject.getString("records"))
      11. System.out.println("Json array Length: "+jarray.length())
      12. for(int j=0
      13. j<jarray.length()
      14. j++) { JSONObject tempObject=jarray.getJSONObject(j)
      15. System.out.println("Timestamp: "+tempObject.getString("timestamp"))
      16. System.out.println("Device Id: "+tempObject.getString("deviceId"))
      17. System.out.println("Temperature: "+tempObject.getString("temperature"))
      18. } } catch(Exception e) { e.printStackTrace()
      19. }}

    25. how to read values from jsonarray?

      girths should be another JSONObject so I guess on your JSONArray . . details

      Reactions - Positive 2, Negative 0, Others 0

      1. try{ Object obj = parser.parse(new FileReader("D:/jdemo.json"))
      2. JSONObject jsonObject = (JSONObject) obj
      3. JSONArray companyList = (JSONArray)jsonObject.get("body_stats")
      4. Iterator<JSONObject> iterator = companyList.iterator()
      5. while (iterator.hasNext()) { JSONObject jsonObject = iterator.next()
      6. Object object = jsonObject.get("girths")
      7. if(object != null){ JSONObject girths = (JSONObject )object
      8. System.out.println(girths)
      9. } } }

      Positive Reactions
      1. Happy to hear it......if it helped you please accept the answer..
      2. @Prabhakaran----------thanx its working.

    26. ClassCastException while casting JSONArray into JSONObject

      You need to parse the values and get the string. . details

      Reactions - Positive 2, Negative 2, Others 0

      1. JSONArray jr = new JSONArray("myjsonstring")
      2. for(int i=0
      3. i<jr.length()
      4. j++) { JSONOBject jb = jr.getJSONObject(i)
      5. String uid = jb.getString("uid")
      6. String status = jb.getString("status")
      7. String name = jb.getString("name")
      8. }

      Positive Reactions
      1. Thanks...
      2. Glad it helped.
      Negative Reactions
      1. The line JSONObject jb jr.getJSONObject(i); solved my problem..
      2. @user2749218 you also had this JSONObject jObject (JSONObject) jArray.get(i); so the problem should be probably here jArray jChild.getJSONArray("users").

    27. How to parse JSON Array (Not Json Object) in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray arr = new JSONArray(jSonResultString)
      2. //loop through each object for (int i=0
      3. i<arr.length()
      4. i++){ JSONObject jsonProductObject = arr.getJSONObject(i)
      5. String name = jsonProductObject.getString("name")
      6. String url = jsonProductObject.getString("url")
      7. }

    28. Simple json like this. creating and parsing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = "{\n" + " \"time\": [\n" + " { \"UserId\": \"Action\"},\n" + " { \"UserId\": \"Action\"}\n" + " ]\n" + "}"
      2. JSONObject jsonRoot = new JSONObject(json)
      3. JSONArray timeArray = jsonRoot.getJSONArray("time")
      4. System.out.println(timeArray)
      5. // prints: [{"UserId":"Action"},{"UserId":"Action"}]

    29. Android Parse JSON stuck on get task

      why do you use an asynctask if you are going to call get on it . You can greatly simplify everything using the droidQuery library . details

      Reactions - Positive 0, Negative 1, Others 0

      1. $.getJSON("http://www.example.com", null, new Function() {//this will run using an AsyncTask, get the JSON, and return either a JSONObject or JSONArray on the UI Thread. @Overrde public void invoke($ droidQuery, Object... params) { if (params[0] instanceof JSONObject) { //it's often ok just to assume a JSONObject, making your first line simply: JSONObject obj = (JSONObject) params[0]
      2. //JSONObject is returned JSONObject json = (JSONObject) params[0]
      3. //to easily parse this Object, convert it to a map first: Map<String, ?> map = $.map(json)
      4. //then you can just make a call like this: if (map.contains("field_currentappversion")) { config.currentAppVersion = (String) map.get("field_currentappversion")
      5. } } else { //JSONArray is returned JSONArray json = (JSONArray) params[0]
      6. //if you got an array, you can easily convert it to an Object[] for parsing: Object[] array = $.makeArray(json)
      7. } }})

      Negative Reactions
      1. This doesn't solve my problem, instead you are suggesting I use some other library.

    30. Parsing JSON server response into JSON Array

      So you're probably trying to get JSONObject instead of String inside the results aarray. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject responseObject = new JSONObject(responseString)
      2. JSONArray resultsArray = responseObject.getJSONArray("results")
      3. for (int i=0
      4. i<resultsArray.length()
      5. i++) String resultString = resultsArray.getString(i)

    31. double quote in json simple

      I want this outcome I tried this The output of ob1.toJSONString is What am I doing wrongly?I am using json-simple-1.1.1 . You should put a JSONArray into the JSONObject and in the Array again a JSONObject with the keys/values url" and label"/"wikipedia In case you have the value of ob1 link object already as JSON string then you can first interpret this into a JSONArray using NOTE Your intended result is not a JSON string because for that all must be escaped . details

      Reactions - Positive 1, Negative 2, Others 0

      1. JSONObject ob1 = new JSONObject()
      2. JSONArray ar1 = new JSONArray()
      3. ob1.put ("link", ar1)
      4. JSONObject ob2 = new JSONObject()
      5. ar1.add(ob2)
      6. ob2.put("url", "http://en.wikipedia.org/wiki/JScript")
      7. ob2.put("label", "wikipedia")

      Positive Reactions
      1. Your string would not be a correct JSON formatted string.
      Negative Reactions
      1. Ah that was dumb of me.
      2. the problem with the url still exists.
      Other Reactions
      1. I don't think so, because json-simple is following the JSON specification.
      2. That is JSON spec.
      3. so it is not possible to get my desired outcome?
      4. I am getting the following and I can't escape the / with \/.
      5. {"link":[{"url":"http:\/\/en.w ikipedia.org\/wiki\/JavaScript","label":"wikipedia"}]}.

    32. Java JSON parse array

      Hope this would solve your problem. Why do you need parser?try this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String stringJson = "{\"name\": \"web\", \"services\": []}"
      2. JSONObject obj = JSONObject.fromObject(stringJson)
      3. System.out.println(obj)
      4. System.out.println(obj.get("name"))
      5. System.out.println(obj.get("services"))
      6. JSONArray arr = obj.getJSONArray("services")
      7. System.out.println(arr.size())

    33. How to make a JSON String using the key/value from the Map

      You're making this way to complicated. You can just do something like this In other words create a new empty JSONObject named rootJo root JSON object iterate over your list of maps for each element in the list convert the map into a JSONObject using a library add a new property to rootJo the key will be v set the value of v to the JSONObject that was created from the map Maybe I'm missing something but I would replace your entire method with this You should also make it typesafe but I'll leave the finer details to you plus I'm not sure what an AttributeValue is can't find it anywhere . details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * Creates a JSON object from a list of attributes that * have maps as their values. */private JSONObject toJson(List<AttributeValue<?>> attList) { if (attList == null) { return null
      2. } JSONObject jo = new JSONObject()
      3. JSONArray ja = new JSONArray()
      4. for (AttributeValue<?> att : attList) { JSONObject mapJo = new JSONObject(att.getValue())
      5. ja.put("v", mapJo)
      6. } jo.put("lv", ja)
      7. return jo
      8. }

    34. Trouble parsing through complicated json

      Oftentimes creating a model like was demonstrated in the previously posted tutorial can be burdensome and way too much work for the effort. Using the org.json library you can chain together your get methods like so And traverse the json in that manner. details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONObject json = new JSONObject(what you put in pastebin)
      2. String string = json.getJSONArray('data') .getJSONObject(0) .getString("name")

      Positive Reactions
      1. Now onto the next thing, figuring out how to put this all into a list view!.
      2. finally learning how JSON WORKS!
      3. that is exactly what i was looking for thank you so much!
      Other Reactions
      1. Going to try that now.

    35. Android - How to parse JSONObject and JSONArrays from api.rottentomatoes

      If you're not going to map to a POJO and instead are going through the JSON you simply need to get that array in your loop after getting movie and get each cast member object from that array in the same manner using another loop. Edit from comments Your original question involved how to extract the information from the JSON you have the above code explains that. details

      Reactions - Positive 1, Negative 0, Others 0

      1. ...JSONArray cast = movie.getJSONArray("abridged_cast")
      2. for (int j = 0
      3. j < cast.length()
      4. j++) { JSONObject castMember = cast.getJSONObject(j)
      5. ... }

      Positive Reactions
      1. Thanks!
      Other Reactions
      1. it worked.
      2. @user2252496 - you'd ... want a data structure that encapsulated that information and allowed you to access it; a Map for example.
      3. Ideally you'd create an actual object (class) in Java that basically mirrored the "movie" object you have in that JSON array which is the normal way to approach these things.
      4. there's a problem with your method... the movie castMember are been save as one big array and every time i press a movie from a list it just give me the name of one actor... how do i save from each movie the actors as an array for just the specific movie and not for all the movies?

    36. How do I clone an org.json.JSONObject in Java?

      I'd like to warn others that this method performs a shallow copy the asker wanted that but don't forget it. Couldn't find an existing deep clone method for com.google.gwt.json.client.JSONObject but the implementation should be few lines of code something like Note:_*I haven't tested it yet. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static JSONValue deepClone(JSONValue jsonValue){ JSONString string = jsonValue.isString()
      2. if (string != null){return new JSONString(string.stringValue())
      3. } JSONBoolean aBoolean = jsonValue.isBoolean()
      4. if (aBoolean != null){return JSONBoolean.getInstance(aBoolean.booleanValue())
      5. } JSONNull aNull = jsonValue.isNull()
      6. if (aNull != null){return JSONNull.getInstance()
      7. } JSONNumber number = jsonValue.isNumber()
      8. if (number!=null){return new JSONNumber(number.doubleValue())
      9. } JSONObject jsonObject = jsonValue.isObject()
      10. if (jsonObject!=null){ JSONObject clonedObject = new JSONObject()
      11. for (String key : jsonObject.keySet()){ clonedObject.put(key, deepClone(jsonObject.get(key)))
      12. } return clonedObject
      13. } JSONArray array = jsonValue.isArray()
      14. if (array != null){ JSONArray clonedArray = new JSONArray()
      15. for (int i=0
      16. i < array.size()
      17. ++i){ clonedArray.set(i, deepClone(array.get(i)))
      18. } return clonedArray
      19. } throw new IllegalStateException()
      20. }

    37. How to read JSON object from URL query string

      You'll want to use a JSON serialization library like Jackson which will write the object to a string in JSON for you. This is what that data would probably look like if it were written in JSON Java code that translates from the above JSON to your-format Your data format does not appear to be standard so you will have to parse it yourself. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject root = new JSONObject(json)
      2. JSONArray filters = root.getJSONArray("filter")
      3. for (int i = 0
      4. i < filters.length()
      5. i++){ JSONObject filter = filters.getJSONObject(i)
      6. String field = filter.getString("field")
      7. JSONObject data = filter.getJSONObject("data")
      8. String dataType = data.getString("type")
      9. String dataValue = data.getString("value")
      10. System.out.println("filter[" + i + "][field]=" + field)
      11. System.out.println("filter[" + i + "][data][type]=" + dataType)
      12. System.out.println("filter[" + i + "][data][value]=" + dataValue)
      13. }

    38. JSONArray cannot be converted to JSONObject given a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject rawJson = new JSONObject ( jsonResponse )
      2. JSONArray categories = rawJson.getJSONArray( "Categories" )

    39. JSONArray cannot be converted to JSONObject given a string

      Try Instead of JSON example in your question is actually a JSON array. So as a result it is going to be Here is some explaination on what is going on with your JSON data.Currently it looks like Is not going to work because there is no object inside this JSON data called Categories" instead it has a String element with value Categories". details

      Reactions - Positive 2, Negative 0, Others 0

      1. ["Categories",[[{"id":"2","name":"Glass Repair"} ....JSONObject jsonObj = new JSONObject(new String(blah))
      2. JSONArray data = jsonObj.getJSONArray("Categories")

      Positive Reactions
      1. Excellent thank you.
      2. Just so anyone who finds this, once the JSON data was formatted correctly, it seemed to work perfectly here is the new output{"Categories":[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Ele ctrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id ":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"R emodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]}.
      Other Reactions
      1. I updated my code to your suggestion and now receive the following in logcat:05-12 03:09:22.185: E/Http Error(21193): Error in http connection org.json.JSONException: Value Categories at 0 of type java.lang.String cannot be converted to JSONObject.
      2. I'll updated the code in the morning and let everyone know how it goes.

    40. Extracting an array from a JSON object

      I'm no expert on JSONObject but if this is part of a loop and i is provided by it this probably will work. Modify your code to something like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy")
      2. if(jsonTaxonomy!=null){ JSONObject jsonTaxonomySource = jsonTaxonomy.optJSONObject("source")
      3. if(jsonTaxonomySource!=null) { JSONArray jsonTaxonomySearsWeb= jsonTaxonomySource.optJSONArray("web")
      4. if(jsonTaxonomySearsWeb!=null) { // Traverse through your JSONArray and get each Object & extract path from it. } }}

    41. Issue parsing JSON Array out of a string

      With a better library you could map the object to a Map<String Object or if the sample you gave is indicative of what your data will always be like you could map it to Map<String String . your JSONObject is actually an array where the first Object key is 1.Try Does that work . details

      Reactions - Positive 4, Negative 0, Others 0

      1. JSONObject json = new JSONArray(jsonString).getJSONObject(0)
      2. // or JSONObject json = new JSONObject(jsonString).getJSONObject("1")
      3. success = json.getBoolean("success")
      4. object = json.getString("object")
      5. message = json.getString("message")
      6. data = json.getJSONArray("data")

      Positive Reactions
      1. Awesome!
      2. Just what I needed thanks!.
      3. Kind of...
      4. Glad to help :) If your problem is solved, accepting an answer would help others that find this question.
      Other Reactions
      1. 1... the keys in this case are actually database unique identifiers which I wouldn't know until after.
      2. There's no way to just create an associative array without knowing what the keys are called?
      3. [JSONObject]( URL_http://www.json.org/javadoc/org/json/JSONObject.html ) has a method .keys() which will return an enumeration of keys in the Object you can use.
      4. But that requires that I know what the key name is - i.e.
      5. I can use json.getJSONObject("data").getJSONObject("1") to get the first element of my array.

    42. Mapping JSON to arrays/objects in Java - Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. userDet = new JSONObject(string)
      2. JSONArray userDetJson = userDet.getJSONArray("steps")

    43. Mapping JSON to arrays/objects in Java - Android

      Try parameter steps instead of Steps". change it to steps and not Steps It will fix it The full parsing method . details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONArray mainArray = new JSONArray(json)
      2. for (int i = 0
      3. i < mainArray.length()
      4. i ++){ JSONObject currentItem = array.getJSONObject(i)
      5. String title = currentItem.getString("title")
      6. String body = currentItem.getString("body ")
      7. .... JSONArray currentItemStepsArray = currentItem.getJSONArray("steps")
      8. for (int j = 0
      9. j < currentItemStepsArray.length()
      10. j ++) { .... }}

      Positive Reactions
      1. Thank you for the full parsing method.
      2. I think that this finally makes sense to me now!.
      3. you welcome, have a nice coding : ).

    44. Reading JSON double dimensional array in Java

      You have an array of objects with each object having a single object in it. However you could read it like this However. details

      Reactions - Positive 3, Negative 3, Others 0

      1. JSONArray jsonArray = new JSONArray (jsonString)
      2. int arrayLength = jsonArray.length ()
      3. for (int counter = 0
      4. counter < arrayLength
      5. counter ++) { JSONObject thisJson = jsonArray.getJSONObject (counter)
      6. // we finally get to the proper object thisJson = thisJson.getJSONObject ("news")
      7. String title = thisJson.getString ("title")
      8. String content = thisJson.getString ("content")
      9. String date = thisJson.getString ("date")
      10. }

      Positive Reactions
      1. thank you anyway for your help!
      2. The array might contain other objects besides "news", so the format of the json is actually pretty descriptive.
      3. I think Shade is right, my json is not as good as he advised, it's just because i'm encoding it using php and this is what i got, i couldn't make it just like you did but i'll try.
      Negative Reactions
      1. No problem.
      2. "Your json is bad" is opinion.
      3. You got wrong date is a string you won't get it using getLong(), check the quotes.
      Other Reactions
      1. You could ask another question for your PHP code that generates the JSON.
      2. @323go he actually says it's a two-dimensional array in the title and in the first line of the question he says "Each news has three things : title,contentand date".
      3. :).
      4. I think he doesn't really understand the syntax of JSON arrays and objects, so I tried to help with an example.

    45. Reading JSON double dimensional array in Java

      However you could read it like this However. You could do better if you change your JSON to look like the following Then you could parse it as follows . details

      Reactions - Positive 3, Negative 3, Others 0

      1. JSONArray jsonArray = new JSONArray (jsonString)
      2. int arrayLength = jsonArray.length ()
      3. for (int counter = 0
      4. counter < arrayLength
      5. counter ++) { // we don't need to look for a named object any more JSONObject thisJson = jsonArray.getJSONObject (counter)
      6. String title = thisJson.getString ("title")
      7. String content = thisJson.getString ("content")
      8. String date = thisJson.getString ("date")
      9. }

      Positive Reactions
      1. thank you anyway for your help!
      2. The array might contain other objects besides "news", so the format of the json is actually pretty descriptive.
      3. I think Shade is right, my json is not as good as he advised, it's just because i'm encoding it using php and this is what i got, i couldn't make it just like you did but i'll try.
      Negative Reactions
      1. No problem.
      2. "Your json is bad" is opinion.
      3. You got wrong date is a string you won't get it using getLong(), check the quotes.
      Other Reactions
      1. You could ask another question for your PHP code that generates the JSON.
      2. @323go he actually says it's a two-dimensional array in the title and in the first line of the question he says "Each news has three things : title,contentand date".
      3. :).
      4. I think he doesn't really understand the syntax of JSON arrays and objects, so I tried to help with an example.

    46. Reading JSON double dimensional array in Java

      Your JSON string is a JSONArray of JSONObject which then contain an inner JSONObject called news". Try this for parsing it . details

      Reactions - Positive 2, Negative 1, Others 0

      1. JSONArray array = new JSONArray(jsonString)
      2. for(int i = 0
      3. i < array.length()
      4. i++) { JSONObject obj = array.getJSONObject(i)
      5. JSONObject innerObject = obj.getJSONObject("news")
      6. String title = innerObject.getString("title")
      7. String content = innerObject.getString("content")
      8. String date = innerObject.getString("date")
      9. /* Use your title, content, and date variables here */}

      Positive Reactions
      1. Thank you it works !
      2. @JonathanHugh I'm glad you were able to find an answer to your question.
      Negative Reactions
      1. Remember that if an answer given meets your needs, you should accept that answer by clicking the check mark under the voting arrows so that people viewing this question in the future will be able to tell which answer solved the problem.
      Other Reactions
      1. :).

    47. How to convert list data into json in java

      thanks good solution. you can get the data in the following form . details

      Reactions - Positive 1, Negative 1, Others 0

      1. public static List<Product> getCartList() { JSONObject responseDetailsJson = new JSONObject()
      2. JSONArray jsonArray = new JSONArray()
      3. List<Product> cartList = new Vector<Product>(cartMap.keySet().size())
      4. for(Product p : cartMap.keySet()) { cartList.add(p)
      5. JSONObject formDetailsJson = new JSONObject()
      6. formDetailsJson.put("id", "1")
      7. formDetailsJson.put("name", "name1")
      8. jsonArray.add(formDetailsJson)
      9. } responseDetailsJson.put("forms", jsonArray)
      10. //Here you can see the data in json format return cartList
      11. }

      Positive Reactions
      1. thnx sir for ur response ..plz sir tell me what to add in this code: " formDetailsJson.put("...", "...");".
      Negative Reactions
      1. Sir i need to know what to add as argument in this "formDetailsJson.put("...", "..."); formDetailsJson.put("...", "...");".
      Other Reactions
      1. you need to put name with which name you are going to access in the javascript.
      2. you need to add related jar files to class path which contain org.json.simple.JSONArray,org.json.simple.JSONObject classes.
      3. sir i am trying to do it like this "formDetailsJson.put("title", "description","price");" but its giving error.
      4. And those jar file i ahave added sir.

    48. java android - iterate JSON objects in array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = (JSONObject) new JSONTokener(/*Json String Data*/).nextValue()
      2. JSONArray jsonArray = jsonObject.getJSONArray(/*Name of JSON Array*/)

    49. To read the json as a string object in android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject mainObject = new JSONObject(strjson)
      2. JSONArray Array = mainObject.getJSONArray("speciality")
      3. for (int j = 0
      4. j < Array.length()
      5. j++) { if (Array.getJSONObject(j).has("id")) { String str1 = (Array.getJSONObject(j).getString("id"))
      6. String str2 = (Array.getJSONObject(j).getString("d_name"))
      7. Log.e("TA","name:"+str2)
      8. } }

    50. To read the json as a string object in android

      Use this . Try this I hope this will be help to you . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject mainObject = new JSONObject(strjson)
      2. JSONArray details= mainObject .getJSONArray("speciality")
      3. if (details.length()!=0) { for (int i = 0
      4. i < details.length()
      5. i++) { String id = details.getJSONObject(i).getString("id")
      6. String name = details.getJSONObject(i).getString("d_name")
      7. ...... ...... String longitude= friends.getJSONObject(i).getString("longitude")
      8. }}

    51. How to parse nested json arrays in a single object in android

      Here is my parsing code Can anyone make me clear about the mistake I have made. So here is my solution . details

      Reactions - Positive 2, Negative 2, Others 0

      1. JSONObject first = new JSONObject(mResponse)
      2. JSONArray locArr = first.getJSONArray("location")
      3. // contains one objectJSONObject locArrObj = locArr.getJSONObject(0)
      4. // cotains one "out" arrayJSONArray conferenceLocArr = locArrObj.getJSONArray("conferencelocation")
      5. // this array has two objects and each object has arrayJSONObject o = null
      6. JSONArray arr = null
      7. for (int i = 0
      8. i < conferenceLocArr.length()
      9. i++) { o = conferenceLocArr.getJSONObject(i)
      10. // it has one array arr = o.getJSONArray("guests")
      11. // do your work with Stage 1 and guests // and for second object for Stage 2 and guests.}

      Positive Reactions
      1. do your work with Stage 1 and guests and Stage 2 and guests.this line is unclear to me, and I m new in json parsing, it wouldbe helpful if u could describe a bit.
      2. I think it is close to my destination , thanks :).
      Negative Reactions
      1. A do not think that solution is too complicated.
      2. I recommned to you read something about JSON on wikipedia for example, then make some app with much less complicated JSON and then look at my solution.
      Other Reactions
      1. { bracket presents JSONObject, ends with }**.
      2. ok, I am trying and I think some one will know about the explaination :).
      3. You have to check your JSON file, read it carefully and look at brackets.
      4. I know about json but not much experienced about nested jsonarray.
      5. So you want to parse JSON and you know anything about format, its not good, in't?
      6. so i dont know how to explain it more.
      7. can you explain a little bit elaborately?
      8. [ bracket presents JSONArray and ends with ]**.
      9. all what you need to know i told you so you need to step application.
      10. So you need to go through JSON "step by step".

    52. How to access nested elements of json object using getJSONArray method

      Please see my example Program output If you not familiar with this library then you can find a lot of informations in Gson-User-Guide . You can try this I hope this helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject result = new JSONObject("Your string here").getJSONObject("result")
      2. JSONObject map = result.getJSONObject("map")
      3. JSONArray entries= map.getJSONArray("entry")

    53. Parse json array android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. try { JSONfunctions j=new JSONfunctions()
      2. JSONArray jArray = j.getJSONfromURL(url)
      3. Log.i("log_tag", jArray.toString())
      4. for(int i=0
      5. i<jArray.length()
      6. i++){ JSONObject json_data = jArray.getJSONObject(i)
      7. String jsonvalues = json_data.getString("id")
      8. // .. get all value here Log.i("DARE", jsonvalues)
      9. } }catch (Exception ex) { Log.e("log_tag", "Error getJSONfromURL "+ex.toString())
      10. }

    54. Keep the order of the JSON keys during JSON conversion to CSV

      Here is the constructor of JSONObject.java class that will do the checking of map. So before building a json object construct LinkedHashMap and then pass it to the constructor like this So there is no need to change the JSONObject.java class . details

      Reactions - Positive 2, Negative 1, Others 0

      1. LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>()
      2. jsonOrderedMap.put("1","red")
      3. jsonOrderedMap.put("2","blue")
      4. jsonOrderedMap.put("3","green")
      5. JSONObject orderedJson = new JSONObject(jsonOrderedMap)
      6. JSONArray jsonArray = new JSONArray(Arrays.asList(orderedJson))
      7. System.out.println("Ordered JSON Fianl CSV :: "+CDL.toString(jsonArray))

      Positive Reactions
      1. It only copy name/value pairs from paramMap to HashMap... :(.
      2. Good answer, works for normal java, but doesn't work on android.
      Negative Reactions
      1. I check the org.json.JSONObject in android, it's a pity that android still use hashmap created internally.

    55. Test if it is JSONObject or JSONArray

      Good edit 1. I haven't tryied it but maybe If it's a JsonArray object just use getAsJsonArray to cast it. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject jRoot = RestManager.getJSONfromURL(myuri)
      2. // retrieve the entire json streamJsonElement interventionElement = jRoot.get("intervention")
      3. JsonArray interventionList = new JsonArray()
      4. if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray())
      5. else interventionList.add(interventionElement)

    56. JSON Java check element is a JSONArray or JSONObject

      tokenizer is able to return more types nextValue . Even though you have got your answer but still it can help other users Here Law is other JSONObject and LawSet is the key which you want to find as JSONObject or JSONArray. details

      Reactions - Positive 0, Negative 0, Others 0

      1. if (Law.get("LawSet") instanceof JSONObject) { JSONObject Lawset = Law.getJSONObject("LawSet")
      2. } else if (Law.get("LawSet") instanceof JSONArray){ JSONArray Lawset = Law.getJSONArray("LawSet")
      3. }

    57. Spring MVC -> JSON response

      You can also use org.json's JSONArray and JSONObject to construct the JSON output then return a String value as the ResponseBody. You should get something like this in your ajax request's success callback. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping(value="/getall", method=RequestMethod.GET)public @ResponseBody String getAllProjects() { ... JSONArray jsonItems = new JSONArray()
      2. JSONObject jsonItem1 = new JSONObject()
      3. jsonItem1.put("id", "1")
      4. jsonItem1.put("name", "My Test Project")
      5. JSONObject jsonItem2 = new JSONObject()
      6. jsonItem2.put("id", "4")
      7. jsonItem2.put("name", "Another one")
      8. jsonItems.put(jsonItem1)
      9. jsonItems.put(jsonItem2)
      10. return jsonItems.toString()
      11. }

      Other Reactions
      1. Is more efficent this solution?
      2. Or is better to use Jackson function writeValueAsString?

    58. Json conversion

      i want to create a Json like this i have tried below code but that create Json just only for one line this above code create Json like this Please let me know about the changes required in that Java code thanks. Change your code as . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONArray jsonArray = new JSONArray()
      2. //Add 1st JSONObject to JSONArrayJSONObject jsonObjone = new JSONObject()
      3. jsonObjone.put("sID", "221")
      4. jsonObjone.put("mID","0")
      5. jsonArray.put(jsonObjone.toString()
      6. //Add 2nd JSONObject to JSONArrayJSONObject jsonObjtwo = new JSONObject()
      7. jsonObjtwo.put("sID", "222")
      8. jsonObjtwo.put("mID","11")
      9. jsonArray.put(jsonObjtwo.toString())
      10. //Add 3rd JSONObject to JSONArrayJSONObject jsonObjthrd = new JSONObject()
      11. jsonObjthrd.put("sID", "223")
      12. jsonObjthrd.put("mID","11")
      13. jsonArray.put(jsonObjthrd.toString())

      Positive Reactions
      1. O yes done thank You very Much Imran Saved alot of my time :-) stay blessed buddy.
      2. most welcome friend!!!
      Other Reactions
      1. @ShYzDaSE : see my edit answer.
      2. why you are converting jsonarray to JSONObject?
      3. Thanks for reply; but it gives error "The method toJSONString() is undefined for the type JSONObject" at jsonArray.push(jsonObj.
      4. _toJSONString()_);.
      5. :).

    59. How to get data as an json array from a server and convert it in to java array to use in android application

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject myjson = new JSONObject(the_json)
      2. JSONArray the_json_array = myjson.getJSONArray("profiles")

    60. Create a JSONArray

      You can create JSONArray same like you have tried to create JSONObject. Creating time For example Retrieving time you can fetch the value of String or JSONObject or any by their key name. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray myArray = new JSONArray()
      2. JSONObject j = new JSONObject()
      3. j.put("key",value)
      4. j.put("array",myArray)

    61. Android how to sort JSONArray of JSONObjects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray kids = node.getJSONArray("contents")
      2. kids = JSONUtil.sort(kids, new Comparator(){ public int compare(Object a, Object b){ JSONObject ja = (JSONObject)a
      3. JSONObject jb = (JSONObject)b
      4. return ja.optString("name", "").toLowerCase().compareTo(jb.optString("name", "").toLowerCase()
      5. }})
      6. // in my case I wanted the original larger object contents sorted...node.put("contents", kids)

    62. Simple code for converting JSONObject to a List or JSONArray?

      I'll take a look though thanks. Thanks to help from a friend and some fiddling I found a solution I'm sure it's not the most eloquent but it's exactly what I was after Thanks for the help and suggestions guys. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for(Object key: orr.keySet()) { JSONArray orderOne = (JSONArray)orr.get(key)
      2. JSONObject ordervalue = (JSONObject)orderOne.get(0)
      3. System.out.println(ordervalue.get("productId"))
      4. }

    63. Simple code for converting JSONObject to a List or JSONArray?

      Those arrays only have one item each which are both objects. So here is an example of fetching the data Now once you've pulled it out you can transform this data into any structure you like to make it more friendly to access from this point forward. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject jsonObject = (JSONObject)orderRows.get("orderRows")
      2. JSONArray firstArray = jsonObject.getJSONArray("470")
      3. JSONArray secondArray = jsonObject.getJSONArray("471")
      4. JSONObject firstObject = firstArray.get(0)
      5. int locationId = firstObject.getId("locationId")
      6. /*...etc...*/

      Positive Reactions
      1. Thanks to help from a friend and some fiddling, I found a solution, I'm sure it's not the most eloquaint, but it's exactly what I was after:.
      Other Reactions
      1. Thanks, problem being I do not know what these numbers 470 and 471 will be, I know them in this case because I've printed them out.Many Thanks.

    64. JSONObject and JSONArray - Need to get values held in array

      What is requestSubObj. I think you should get the objects like this Also you need to call for the ids object . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject item3Holder = requestObj.getJSONObject("item3Holder")
      2. JSONArray ids = item3Holder.getJSONArray("ids")

      Positive Reactions
      1. that worked great thanks very much.

    65. Creating a JSON object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.test.json
      2. import org.json.simple.JSONArray
      3. import org.json.simple.JSONObject
      4. public class JsonSimpleExample {
      5. public static void main(String[] args) {
      6. JSONObject obj = new JSONObject()
      7. obj.put("method", "SearchBySearchConfiguration")
      8. JSONArray list = new JSONArray()
      9. JSONObject innerObj = new JSONObject()
      10. innerObj.put("SearchCriteria", "%arriva")
      11. innerObj.put("IsAccountSearch", true)
      12. innerObj.put("IsContactSearch", false)
      13. innerObj.put("SearchByName", true)
      14. innerObj.put("SearchByAddress", false)
      15. innerObj.put("CRMTextValues", new JSONArray())
      16. innerObj.put("CRMCurrencyValues", new JSONArray())
      17. list.add(innerObj)
      18. obj.put("params", list)
      19. System.out.print(obj)
      20. }
      21. }

    66. Creating a JSON object

      In both cases once you get the json string you can directly write it into the request body. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json=new JSONObject()
      2. json.put("method", "SearchBySearchConfiguration")
      3. JSONArray paramsArr = new JSONArray()
      4. JSONObject arrobj = new JSONOject()
      5. arrobj.put("SearchCriteria","%arriva")
      6. arrobj.put("IsAccountSearch","true")
      7. arrobj.put("IsContactSearch","false")
      8. arrobj.put("SearchByName","true")
      9. arrobj.put("SearchByAddress","false")
      10. arrobj.put("CRMTextValues",new JSONArray())
      11. arrobj.put("CRMCurrencyValues",new JSONArray())
      12. paramsArr.put(arrobj)
      13. json.put("params",paramsArr)

    67. Create json object in servlet

      Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet . details

      Reactions - Positive 3, Negative 0, Others 0

      1. try{ Class.forName("com.mysql.jdbc.Driver").newInstance()
      2. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root")
      3. Statement st=con.createStatement()
      4. ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'")
      5. int i=0
      6. JSONArray jArray = new JSONArray()
      7. while(rs.next()){ String s = rs.getString("atmbrno")
      8. String t = rs.getString("atmbrname")
      9. JSONObject arrayObj = new JSONObject()
      10. arrayObj.put("atmbrno",s)
      11. arrayObj.put("atmbrname",t)
      12. jArray.add(i,arrayObj)
      13. i++
      14. } rs.close ()
      15. st.close ()
      16. out.print(jArray)
      17. }

      Positive Reactions
      1. Thanks @ColdHack I updated my answer.
      2. Wel done Bro...U r the best..it's working :D :D there is small thing wrong in ur code, jArray.put(i,arrayObj); and it should correct as jArray.add(i,arrayObj);Thanks again :D :D :D.
      3. ya i updated now thanks :).

    68. Android: get all JSON values froma a certain category

      I have found the solution here is the working example. If this can help you please enjoy. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < jsonArrayFrench.length()
      3. i++) { JSONArray innerJsonArray = jsonArrayFrench.getJSONArray(i)
      4. for (int j=0
      5. j < innerJsonArray.length()
      6. j++) { JSONObject jsonObject = innerJsonArray.getJSONObject(j)
      7. if(jsonObject.getString("category").equals(category)) subnewsFrench.add(jsonObject.getString("title"))
      8. } }

    69. JSON to Java Object

      Thanks. Using the excellent json-simple library you should be able to do something like this Obviously replace the literal JSON text with the data that you're fetching from your database. details

      Reactions - Positive 1, Negative 1, Others 0

      1. String json = "[{\"photo\": \"1.png\"}, {\"photo\": \"2.png\"}, " + "{\"photo\": \"3.png\"}, {\"photo\": \"4.png\"}]"
      2. JSONArray photos = (JSONArray)JSONValue.parse(json)
      3. for (int index = 0
      4. index < photos.size()
      5. index++) { JSONObject photoObj = (JSONObject)photos.get(index)
      6. System.out.println(photoObj.get("photo"))
      7. }

      Positive Reactions
      1. Also thanks!
      Negative Reactions
      1. This also did the trick.

    70. creating json string using JSONObject and JSONArray

      I believe that you're organizing your data backwards. It seems that you want to use an array of NewsItems and if so then your java JSON generation code should look like this Now your JSON string will look something like this Assuming that your NewsItem gettors return Strings. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = new JSONObject()
      2. JSONArray arr = new JSONArray()
      3. for(int i = 0
      4. i< list.size()
      5. i++){ p = list.get(i)
      6. obj.put("id", p.getId())
      7. obj.put("title", p.getTitle())
      8. obj.put("date". new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()))
      9. obj.put("txt", getTrimmedText(p.getText()))
      10. arr.put(obj)
      11. obj = new JSONObject()
      12. }

      Positive Reactions
      1. Thanks !!
      Other Reactions
      1. ?
      2. @JAVAGeek: javascript arrays have a length property, see edit.
      3. how can i traverse each object in a loop....arr[0] .. arr[1] would be ok but if i don't know number of items then how can i access them ??
      4. i think this is exactly what i was looking for..

    71. creating json string using JSONObject and JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. final JSONArray arr = new JSONArray()
      2. for(int i = 0
      3. i< list.size()
      4. i++) { final JSONObject obj = new JSONObject()
      5. p = list.get(i)
      6. obj.add("id", p.getId())
      7. obj.add("title", p.getTitle())
      8. obj.add("date", new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()))
      9. obj.add("txt", getTrimmedText(p.getText()))
      10. arr.add(obj)
      11. }

    72. parsing json with jackson java

      Thomas added json. wrote my own method which parses json of such structurehere is the code the prodblem was that items are in the array and items is the only element. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static List parseList(String jsonInput, Class clazz) { List result = new LinkedList()
      2. JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonInput)
      3. JSONObject items = (JSONObject)json.getJSONObject(0)
      4. JSONArray dataArrayJSON = (JSONArray)items.getJSONArray("items")
      5. for (int i = 0
      6. i < dataArrayJSON.size()
      7. i++) { result.add(JSONObject.toBean(dataArrayJSON.getJSONObject(i).getJSONObject("item"), clazz))
      8. } return result
      9. }

    73. Extract different values returned in json format using GET REST call

      After creating a JSONArray from this string calling on it would get you a JSONObject for the array's first element which is what actually contains the data in the example you've posted). Assuming the structure you posted you'd need to do something like this After that you can work with nodeObject like any other JSONObject. details

      Reactions - Positive 3, Negative 2, Others 0

      1. JSONArray outerArray = new JSONArray(Result)
      2. JSONObject nodeObject = outerArray.getJSONObject(0)

      Positive Reactions
      1. I have googled a lot and I am not gettin any good tutorial for the same.
      2. In using JSONArray , I have to declare a JSONObject?How can I extract the values from this.the values of latitude and longitude.
      3. Can you please provide me a good link, or tutorial in extracting the information form this using JSONArray.
      Negative Reactions
      1. when I am declaring the JSONArray it is giving me an error.
      2. Yes I have imported this: import java.org.json.JSONArray;it is giving me an error package java.org.json does not exist.
      Other Reactions
      1. ?
      2. Have you imported org.json.JSONArray?
      3. Or can you explain with an example.

    74. Add data to JSONObject

      . The answer is to use a JSONArray as well and to dive deep into the tree structure This code sample uses the api from here . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray arr = new JSONArray()
      2. arr.put (...)
      3. // a new JSONObject()arr.put (...)
      4. // a new JSONObject()JSONObject json = new JSONObject()
      5. json.put ("aoColumnDefs",arr)

      Positive Reactions
      1. +1 for a good and simple answer, keep it up... ;).

    75. How to parse a JSONArray of JSONObjects in JAVA?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. final JSONArray result_array = json.getJSONArray("result")
      2. for (int i = 0
      3. i < result.length()
      4. i++) {JSONObject joObject = result_array.getJSONObject(i)
      5. String jName = joObject.get("referral_fullname").toString()
      6. String jbalance = joObject.get("referral_balance").toString()
      7. }

    76. Array of parameters in a JSONObject using JAVA

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject outer = new JSONObject()
      2. JSONObject inner = new JSONObject()
      3. JSONArray array = new JSONArray()
      4. outer.put("sun", "yellow")
      5. array.put("apple", "red")
      6. array.put("bannanna", "yellow")
      7. array.put("melon", "orange")
      8. inner.put(array)
      9. outer.put("Vegtables":inner)

    77. How to read json file into java with simple JSON library

      Therefore your parser will return a JSONArray. You can then get JSONObjects from the array For reference see Example 1 on the simple/wiki/DecodingExamples json-simple-decoding-example page. details

      Reactions - Positive 2, Negative 1, Others 0

      1. JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"))
      2. for (Object o : a) { JSONObject person = (JSONObject) o
      3. String name = (String) person.get("name")
      4. System.out.println(name)
      5. String city = (String) person.get("city")
      6. System.out.println(city)
      7. String job = (String) person.get("job")
      8. System.out.println(job)
      9. JSONArray cars = (JSONArray) jsonObject.get("cars")
      10. for (Object c : cars) { System.out.println(c+"")
      11. } }

      Positive Reactions
      1. Well, you want to process all of the items in the array in a loop.
      2. Thanks.
      Negative Reactions
      1. @billz: I don't have the library to be able to execute and test this -- but I've edited the answer with my guess.
      Other Reactions
      1. I have tried that but it did not work.
      2. It reads the first object course, instructor, students array and title object.
      3. My code just gets you the first item (a.get(0)) because that was the closest match to your original code.
      4. How can I read the next ones too?
      5. Can you give me a code example.
      6. Is that enough to go on?
      7. The json-simple documentation says a JSONArray is java.util.List, so you can iterate over the elements just like you would a normal list.

    78. Android ArrayList<String[]> to PHP

      Am I missing something. Try the following when generating json string in android . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject JSONSend= new JSONObject()
      2. JSONArray ja = null
      3. JSONArray tmp = new JSONArray()
      4. for(String s[] : Items){ ja = new JSONArray()
      5. for(int i = 0
      6. i<s.length
      7. i++) ja.put(s[i])
      8. tmp.put(ja)
      9. }JSONSend.put("Items", tmp)

      Positive Reactions
      1. This looks like it should work correctly :-).
      2. i used "JSONSend.put("Items", tmp));" instead and it's working as i wanted, thanks.

    79. Read an array of JSON in JAVA

      I hope this will be helpful for you. Something like this . details

      Reactions - Positive 1, Negative 1, Others 0

      1. final String incomingJSON
      2. final JSONArray objArray = new JSONArray(incomingJSON)
      3. for(int i = 0
      4. i < objArray.length()
      5. i++) { final JSONObject obj = objArray.getJSONObject(i)
      6. final User user = getUserFromJson(obj)
      7. }

      Positive Reactions
      1. Value org.apache.http.message.BasicHttpResponse@4636f428 of type java.lang.String cannot be converted to JSONArray.
      Negative Reactions
      1. it give problem since the creation of the JSONArray...
      Other Reactions
      1. Whats the exact problem it gives, please be specific.

    80. How to convert the following json string to java object?

      It might get a little more complicated when you're doing the arrays if you prefer to do all of the parsing manually also pretty easy check out and download the Java source for the Json parser objects. One JSON implementation Use as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. // Construct the JSON object ... final JSONObject json = new JSONObject(jsonString)
      2. // Get 'libraryname' ... final String libraryName = json.getString("libraryname")
      3. // Get 'mymusic' details ... final JSONArray music = json.getJSONArray("mymusic")
      4. final JSONObject entry = music.get(0)
      5. final String song = entry.getString("song")

    81. Parsing JSON and save them on SQLite Database

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonArray = new JSONArray(String input)
      2. JSONObject location = jsonArray.getJSONObject(0).getJSONObject("location")

    82. java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

      LogCat recipePage request.java Many Thanks . Start looking on line 44 of recipePage.java MORE DETAILS Following line is not filling jsondefs . details

      Reactions - Positive 0, Negative 1, Others 0

      1. ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp)

      Negative Reactions
      1. Sorry for the delayed reply: Would it help if I posted my request.java?

    83. Test if it is JSONObject or JSONArray

      Thanks . Something like this should do it This has the advantage of getting the property value from the main JSONObject just once. details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONObject json
      2. Object intervention
      3. JSONArray interventionJsonArray
      4. JSONObject interventionObject
      5. json = RestManager.getJSONfromURL(myuri)
      6. // retrieve the entire json stream Object intervention = json.get("intervention")
      7. if (intervention instanceof JSONArray) { // It's an array interventionJsonArray = (JSONArray)intervention
      8. }else if (intervention instanceof JSONObject) { // It's an object interventionObject = (JSONObject)intervention
      9. }else { // It's something else, like a string or number}

      Positive Reactions
      1. Thanks Budy.
      2. Thanks.
      3. Wonderful !
      Other Reactions
      1. :).

    84. How to check whether the given object is object or Array in JSON string

      Add to that the fact that JSONObject has a get method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions and there ya go. . details

      Reactions - Positive 3, Negative 4, Others 0

      1. if (!json.isNull("URL")){ // Note, not `getJSONArray` or any of that. // This will give us whatever's at "URL", regardless of its type. Object item = json.get("URL")
      2. // `instanceof` tells us whether the object can be cast to a specific type if (item instanceof JSONArray) { // it's an array JSONArray urlArray = (JSONArray) item
      3. // do all kinds of JSONArray'ish things with urlArray } else { // if you know it's either an array or an object, then it's an object JSONObject urlObject = (JSONObject) item
      4. // do objecty stuff with urlObject }}else{ // URL is null/undefined // oh noes}

      Positive Reactions
      1. Thanks Chao.
      2. Well, a boolean can only have two states, and you have three possible outcomes.
      3. Thanks.
      Negative Reactions
      1. Break things up a little.
      2. So I am getting error for that also.
      3. if(!myconf.isNull("URL")||(myconf.getJSONArray("U RL")!=null)||myconf.getJSONArray("URL").length()>0) {Object item myconf.get("URL"); //other code} I am getting exception JSONObject["URL"] not found.
      4. K, first off, quit stuffing everything on one line.
      Other Reactions
      1. I have edited my question may be it will make more sense what I am wondering about.
      2. The instanceof operator will tell you if item is a JSONArray.
      3. I mean the Json contains nothing i.e.
      4. Actually it worked.
      5. Can you give example for if (item instanceof JSONArray).
      6. Hold on, lemme flesh it out a bit.
      7. What should I put in if condition?
      8. You're going to have to do different stuff based on whether it's null, or an array, or an object, right?
      9. Actually I have edited the question also.
      10. But the string can be empty also.
      11. That is the example.
      12. @Judy: What do you mean by "the string can be empty"?
      13. myconf= { } Hence there will be no URL also in the string.

    85. Json Array not properly generated

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray ja = new JSONArray()
      2. while (products.readRecord()){ String productID = products.get("user")
      3. int j = Integer.parseInt(productID, 10)
      4. if(j == userId) { JSONObject jo = new JSONObject()
      5. itemid = products.get("item")
      6. jo.put("item", itemid)
      7. ja.add(jo)
      8. }} out.println(ja)
      9. products.close()

    86. How to nest objects when building JSON with JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray properties = new JSONArray()
      2. properties.put("resume")
      3. properties.put("genre")
      4. properties.put("studio")
      5. ...JSONObject params = new JSONObject()
      6. params.put("properties", properties)
      7. obj.put("params", params)

    87. Getting the string value from a JSON array's object in Java

      . List is your key because that is the property of the outermost JSON object . details

      Reactions - Positive 2, Negative 1, Others 0

      1. JSONObject json = new JSONObject( jsonString )
      2. JSONArray array = json.getArray( "List" )

      Positive Reactions
      1. I can get to the Array just fine.
      2. A simple getString(int i) would do it.
      Negative Reactions
      1. The problem is when I get the Array and have to print the array.getJSONObject(i);.
      Other Reactions
      1. What "Key" are you referring to if it's not "List"?
      2. Normally I would be able to do it by using jsonObject.getString("KEY") but I don't have one here.
      3. So you were asking how to iterate over the array.
      4. Whatever.
      5. I actually found the answer.
      6. You question barely made sense, but if you are saying that you aren't asking about using "List" then what are you talking about?
      7. How can I do that without using a key?
      8. Seriously?

    88. Using Java to decode JSON array of objects

      HotLicks I have edited the question. Instead of casting your Object to JSONArray you should do it like this . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray mJsonArray = new JSONArray(jsonString)
      2. JSONObject mJsonObject = new JSONObject()
      3. for (int i = 0
      4. i < mJsonArray.length()
      5. i++) { mJsonObject = mJsonArray.getJSONObject(i)
      6. mJsonObject.getString("0")
      7. mJsonObject.getString("id")
      8. mJsonObject.getString("1")
      9. mJsonObject.getString("name")
      10. }

      Positive Reactions
      1. It worked....thanks !.

    89. ANR force close when running this code

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private class GetServerVerCode extends AsyncTask<Void, Void, Boolean> {
      2. @Override
      3. protected Boolean doInBackground(Void... params) {
      4. try {
      5. String verjson = NetworkTool.getContent(Config.UPDATE_SERVER + Config.UPDATE_VERJSON)
      6. JSONArray array = new JSONArray(verjson)
      7. if (array.length() > 0) {
      8. JSONObject obj = array.getJSONObject(0)
      9. try {
      10. newVerCode = Integer.parseInt(obj.getString("verCode"))
      11. newVerName = obj.getString("verName")
      12. } catch (Exception e) {
      13. newVerCode = -1
      14. newVerName = ""
      15. return false
      16. }
      17. }
      18. } catch (Exception e) {
      19. return false
      20. }
      21. return true
      22. }
      23. @Override
      24. protected void onPostExecute(Boolean result) {
      25. if (result) {
      26. int vercode = Config.getVerCode(this)
      27. if (newVerCode > vercode) {
      28. doNewVersionUpdate()
      29. } else {
      30. notNewVersionShow()
      31. }
      32. }
      33. }
      34. }

    90. Parsing JSON from YouTube API

      You're almost there. What you need is Then you can traverse over each video . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject(data)
      2. JSONObject dataObject = json.getJSONObject("data")
      3. // this is the "data": { } partJSONArray items = dataObject.getJSONArray("items")
      4. // this is the "items: [ ] part

      Other Reactions
      1. It depends on what you want to do with it.
      2. Thank you for the reply but would I insert this code into the getVideoJSON method, make it void and remove the getVideoData method ?
      3. I don't know what you're attempting to do with the data, but this code should give you a general idea of how to get each videos title and id (and more) out of all the video results.

    91. Getting JSONObject from JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject object = new JSONObject(result)
      2. String syncresponse = object.getString("syncresponse")
      3. JSONObject object2 = new JSONObject(syncresponse)
      4. String synckey = object2.getString("synckey")
      5. JSONArray jArray1 = object2.getJSONArray("createdtrs")
      6. JSONArray jArray2 = object2.getJSONArray("modtrs")
      7. JSONArray jArray3 = object2.getJSONArray("deletedtrs")
      8. for(int i = 0
      9. i < jArray3 .length()
      10. i++){ JSONObject object3 = jArray3.getJSONObject(i)
      11. String comp_id = object3.getString("companyid")
      12. String username = object3.getString("username")
      13. String date = object3.getString("date")
      14. String report_id = object3.getString("reportid")
      15. }

    92. Getting JSONObject from JSONArray

      Here is your json and it's parsing . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs")
      2. for(int i = 0
      3. deletedtrs_array.length()
      4. i++){ JSONObject myObj = deletedtrs_array.getJSONObject(i)
      5. }

    93. Getting JSONObject from JSONArray

      Check this Android JSON Parsing tutorial . JSONArray objects have a function you can loop through all of the JSONObjects by writing a simple for-loop . details

      Reactions - Positive 5, Negative 0, Others 0

      1. for(int n = 0
      2. n < JSONArray.length()
      3. n++){ JSONObject object = JSONArray.getJSONObject(n)
      4. // do some stuff....}

      Positive Reactions
      1. I wrote it like this for readability and clarity, but when you implement it in your own code, your addition makes it more efficient.
      2. You're welcome.
      3. was a bit involved in the code..got a bit late..hope ya don't mind :).
      4. it worked..thanks again.
      5. thanks will try it now...
      Other Reactions
      1. @Lars I know this is already quite old, but for anyone who still needs this and comes here: wouldnt it be better (performance/memory-wise) to put JSONObject object; before the loop, and simply overwrite the existing object instead of possibly creating tons of temporary objects?
      2. You should mark this solution as the answer :-).
      3. @BenjaminSchwalb You're right, that would be better.

    94. How do I send a json object from my rest service so I can parse in out on the client side javascript

      Just create a simple POJO like this Then return this object from your RESTful webservice . index.jsp . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @GET @Produces("application/json") @Consumes("application/json") @Path("/status") // server:8080/server/rest/status public String getStatus( @Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception { // Create a string to hold JSON String json
      2. Collection<Server> svr = SomeHashMap.getStuff().values()
      3. JSONArray jArray = new JSONArray()
      4. for (Server i : svr) { JSONObject m = new JSONObject()
      5. ServerStatus status = i.getStatus()
      6. m.put("id", i.getId())
      7. m.put("name", i.getName())
      8. m.put("status", status.getState())
      9. jArray.add(m)
      10. } json = jArray.toString()
      11. } response.setContentType("text/javascript")
      12. response.getOutputStream().print(json)
      13. response.flushBuffer()
      14. return null
      15. }

      Other Reactions
      1. all credit to mkro above in the comments.

    95. How to loop through JSON parameters in android

      Thanks . Get tracking_users as JSONArray then loop them as JSONObject and with the JSONObject you can get it's properties try this . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray tracking_users = obj.getJSONArray("tracking_users")
      2. for (int i = 0
      3. i < tracking_users.length()
      4. i++) { JSONObject user = tracking_users.getJSONObject(i)
      5. String _id = user.getString("_id")
      6. and etc..}

      Positive Reactions
      1. Perfect, thank you so much.

    96. Json object from database in java

      Which database tables column mentioned above stores the json values. If you want to extract the data from the DB and construct the JSON Object yourself you can do now jObjDeviceList contains all the data. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonArray jArray = new JsonArray()
      2. while (result.next()){ String type_json=result.getString("type")
      3. String name_json=result.getString("name")
      4. String id_json=result.getString("demo")
      5. JsonObject jObj = new JsonObject()
      6. jobj.put("id", id_json)
      7. jobj.put("type", type_json)
      8. jobj.put("name", name_json)
      9. jArray.put(jObj)
      10. }JsonObject jObjDevice = new JsonObject()
      11. jObjDevice.put("device", jArray)
      12. JsonObject jObjDeviceList = new JsonObject()
      13. jObjDevice.put("devicelist", jObjDevice )

    97. JSON - Iterate through JSONArray

      The following code does exactly that. . details

      Reactions - Positive 4, Negative 1, Others 0

      1. import org.json.JSONArray
      2. import org.json.JSONObject
      3. public class Foo {
      4. public static void main(String[] args) throws Exception {
      5. String jsonInput =
      6. "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}"
      7. // "I want to iterate though the objects in the array..." JSONObject outerObject = new JSONObject(jsonInput)
      8. JSONObject innerObject = outerObject.getJSONObject("JObjects")
      9. JSONArray jsonArray = innerObject.getJSONArray("JArray1")
      10. for (int i = 0, size = jsonArray.length() i < size i++) {
      11. JSONObject objectInArray = jsonArray.getJSONObject(i)
      12. // "...and get thier component and thier value." String[] elementNames = JSONObject.getNames(objectInArray)
      13. System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length)
      14. for (String elementName : elementNames) {
      15. String value = objectInArray.getString(elementName)
      16. System.out.printf("name=%s, value=%s\n", elementName, value)
      17. }
      18. System.out.println()
      19. }
      20. }
      21. } /*OUTPUT:3 ELEMENTS IN CURRENT OBJECT:name=A, value=aname=B, value=bname=C, value=c5 ELEMENTS IN CURRENT OBJECT:name=D, value=d4name=E, value=e5name=A, value=a1name=B, value=b2name=C, value=c34 ELEMENTS IN CURRENT OBJECT:name=D, value=ddname=A, value=aaname=B, value=bbname=C, value=cc*/

      Positive Reactions
      1. I want iterate though each of them and get thier component name and value.
      2. I want to iterate though the objects in the array and get thier component and thier value.
      3. Thanks again.
      4. Programmer Bruce: I dont want to get the name for a specific element, I want to check if the array has 4 element, then get thier name and thier value or if the array has 5 elements then get thier name and value.
      Negative Reactions
      1. Iam sorry man, sometimes I even confuess myself.
      Other Reactions
      1. Updated answer per latest requirements.
      2. In my example the first object has 3 components, the scond has 5 and the third has 4 components.
      3. You keep changing the requirements.
      4. To check the number of elements in a JSON object, you can use JSONObject.getNames(objects).length.
      5. To check the number of object components in the array, use getArray.length().
      6. Are you checking if the array has 4 object components, or if an object in the array has 4 elements?
      7. All of the pieces of the code necessary to do what you want are already posted on this page.
      8. This code should do what I want to do.

    98. Getting data from JSON

      The number of items in the two JSON lists are relatively few so I wouldn't be concerned about excessive memory consumption. this is a little rough but I hope you get the idea . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray allData
      2. JSONObject individualMovie
      3. JSONArray backDrops
      4. JSONObject single_backdrop
      5. allData = someMethodToGetJsonFromUrl
      6. int movieCount = 0
      7. while(!allData.isNull(movieCount)){ individualMovie = allData.optJSONObject(showCount)
      8. backDrops = individualMovie.optJSONArray("backdrops")
      9. //WE now have all the backdrops to movie0 //to get the data from the FIRST backdrop: single_backdrop = backDrops.optJSONObject(0).optJSONbject("image")
      10. //NOW we can access the id/url/height/width String URL = single_backdrop.optString("url")
      11. //do something with url movieCount++
      12. //loop through all movies}

    99. Android,trying to parse json data for android

      Which line is it failing on. I would get rid of this line and do this instead I believe this is correct nonetheless please study this tutorial it will work for you client-at-android Android-as-a-Restful-Client . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject json_data = new JSONObject(result)
      2. JSONArray nameArray = json_data.names()
      3. JSONArray valArray = json.toJSONArray(nameArray)

      Positive Reactions
      1. Thanks for your help!!
      Other Reactions
      1. !.
      2. Thanks, it solved my problem.
      3. I mean in this line JSONArray valArray json.toJSONArray(nameArray);.
      4. what is json on your code?

    100. parsing json with java

      To get past the ClassCastException you just need to make the change it's telling you to make to handle the input as an array and not as an object. And here's an example of getting each hotel name. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s)
      2. JSONObject json = (JSONObject) outerArray.get(0)
      3. JSONArray jarray = json.getJSONArray("hotels")
      4. for (int i = 0
      5. i < jarray.size()
      6. i++){ System.out.println("jarray [" + i + "] --------" + jarray.getString(i))
      7. }

      Positive Reactions
      1. Thanks a lot for your answer... :).

    101. parsing json with java

      And here's an example of getting each hotel name. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s)
      2. JSONObject json = (JSONObject) outerArray.get(0)
      3. JSONArray jarray = json.getJSONArray("hotels")
      4. for (int i = 0
      5. i < jarray.size()
      6. i++){ JSONObject hotel = jarray.getJSONObject(i)
      7. String name = hotel.getString("name")
      8. System.out.println(name)
      9. }

      Positive Reactions
      1. Thanks a lot for your answer... :).

    102. Convert a JSON string to object in Java?

      If you click the html links there you can find anything you want. In short to create a json object and a json array the code is o1 o2 can be primitive types long int boolean) Strings or Arrays. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj = new JSONObject()
      2. obj.put("variable1", o1)
      3. obj.put("variable2", o2)
      4. JSONArray array = new JSONArray()
      5. array.put(obj)

    103. Convert a JSON string to object in Java?

      The reverse process is fairly simple I mean converting a string to json object/array. In order to be correctly parsed you just have to know if you are parsing an array or an object. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String myString
      2. JSONObject obj = new JSONObject(myString)
      3. JSONArray array = new JSONArray(myString)

    104. Help parsing Yahoo search results with JSON Not a JsonArray exception

      As far as I know you need to just assume that it could be either and code accordingly. You could wrap the messy details in a helper function like . details

      Reactions - Positive 4, Negative 0, Others 0

      1. JSONArray getArrayOrObject(JSONObject parent, String name) { JSONArray results = parent.optJSONArray(name)
      2. if (results == null) { results = new JSONArray()
      3. JSONObject object = parent.optJSONObject("Result")
      4. if (object != null) { results.put(object)
      5. } } return results
      6. }

      Positive Reactions
      1. Thank you so much!.
      2. If this or other answers helped you, you can indicate so by giving them an upvote and marking the best answer as the "correct" one by checking the checkbox next to it.
      3. PERFECT!
      4. @Dave in VB Glad to be helpful.
      Other Reactions
      1. I don't know why it never crossed my mind to just create the array and stuff the object into it if need be.

    105. Reading a Json Array in android

      In your case change your code to have a JSONObject instead. . details

      Reactions - Positive 5, Negative 0, Others 0

      1. JSONObject json = new JSONObject(jsonString)
      2. JSONArray jArray = json.getJSONArray("list")
      3. System.out.println("*****JARRAY*****"+jArray.length())
      4. for(int i=0
      5. i<jArray.length()
      6. i++){ JSONObject json_data = jArray.getJSONObject(i)
      7. Log.i("log_tag","_id"+json_data.getInt("account")+ ", mall_name"+json_data.getString("name")+ ", location"+json_data.getString("number")+ ", telephone"+json_data.getString("url")+ ",----"+json_data.getString("balance")+ ",----"+json_data.getString("credit")+ ",----"+json_data.getString("displayName") )
      8. }

      Positive Reactions
      1. tks man this works for me.
      2. It works thank you very much.
      3. Don't forget to accept an answer!
      4. Great, glad to have been of help.
      5. Great!!
      Other Reactions
      1. :-).

    106. Reading a Json Array in android

      tks man this works for me. You first need to create a JSONObject to get the Array from something like this should work . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(jsonString)
      2. JSONArray jArray = jsonObject.getJSONArray("list")

      Positive Reactions
      1. It works.
      2. thanks matt.

    107. How do I provide the following json output using java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray inner = new JSONArray()inner.add(1)
      2. inner.add("text")
      3. JSONObject outer = new JSONObject()
      4. outer.put("data",inner)
      5. outer.put("label", "stuff")
      6. String out = outer.toString()

    108. json in java getting the correct values from a list

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject rootJson = new JSONObject(jsonString)
      2. JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult")
      3. //Let's assume we need names....String[] names = null
      4. if (jsonArray != null) { names = new String[jsonArray.length()]
      5. for (int i = 0
      6. i < jsonArray.length()
      7. i++) { JSONObject json = jsonArray.getJSONObject(i)
      8. names[i] = json.getString("Name")
      9. }}//Testfor (String name: names) { System.out.println(name)
      10. }

    109. Problem parsing this YQL JSON in Java/Android

      How can I parse this correctly. You need an extra JSONObject access to get to the query object . details

      Reactions - Positive 3, Negative 2, Others 0

      1. JSONObject query = json.getJSONObject("query")
      2. JSONObject results = query.getJSONObject("results")
      3. JSONArray quotes = results.getJSONArray("quotes")

      Positive Reactions
      1. Thanks!
      2. Ah just noticed the extra layer after results, I edited the original post check to see if that works.
      3. Now it's printing the value of the first Quote in the JSON in the debugger: org.json.JSONException: Value {"quote": ...
      Negative Reactions
      1. The exception occurs on JSONArray quotes query.getJSONArray("results");.
      2. Looks like I still get an Exception though.

    110. Need help with json parsing

      BalusC its tagged in java I'm interested in how can it be done in java. . details

      Reactions - Positive 3, Negative 1, Others 0

      1. JSONObject json = new JSONObject( "{\"members\":[[\"sd2840d\",\"Johny\"],[\"jkld341\",\"Marry\"]]}")
      2. JSONArray array = json.getJSONArray("members")
      3. for (int idx = 0
      4. idx != array.length()
      5. idx++) { JSONArray array2 = array.getJSONArray(idx)
      6. System.out.println(array2.getString(0))
      7. System.out.println(array2.getString(1))
      8. }

      Positive Reactions
      1. @Jim Blackler thank you , I get this error msg :Error: A JSONObject text must begin with '{' at character 1.
      2. works here for me, so maybe you did an error copying.
      3. Funny, are you using 'org.json.JSONObject'?
      Negative Reactions
      1. This error is on the first line?
      Other Reactions
      1. @Jim Blackler Yes and array import org.json.JSONArray;import org.json.JSONObject;.
      2. what package are you using for this JSONObject?
      3. I have run this code and it does work for me.

  3. Converting the Database details to JSON object

    First of all what you have to do is retrieve the data from the columns of the table using your DAO and calling a Function from DAOIMPL which in turn will return the list of data(POJO probably). Create a map like this which will contain your key value pair for example recordid and value,recordname and value . .. details

    1. Map<String,Object> objMap = new HashMap<String,Object>()
    2. objMap.put("recordId", Record.getId())
    3. objMap.put("recordName",Record.getName())
    4. // Now here is the deal create another hashmap here whose key will be records "the key for your second array" //Put the values in this second hashmap as instructed above and put it as a key value pair. ........ ....... ....... JSONObject JsonObject = JSONObject.fromObject(objMap)
    5. //This will create JSON object out of your hashmap. objJSONList.add(JsonObject)
    6. }StringBuffer jsonBuffer = new StringBuffer()
    7. jsonBuffer.append("{\"data\": {")
    8. jsonBuffer.append(objJSONList.tostring())
    9. jsonBuffer.append("}")
    10. //jsonBuffer.append(",\"total\":"+ objJSONList.size())
    11. // TOTAL Optional //jsonBuffer.append(",\"success\":true}")
    12. //SUCCESS message if using in callback Optional

    • See Also (243)
    1. When using JSON in Fragments the app is not responding in Android Development

      If you are testing then ok All network related operation must be done in a background thread. You have And in JSONParser Running NetworkRelated operation on the ui thread. details

      Reactions - Positive 7, Negative 9, Others 0

      1. JSONObject json = jParser.getJSONFromUrl(url)

      Positive Reactions
      1. before that it was working fine.
      2. If not me there are others many talented and your problem will be resolved soon.
      3. In the postExecute how to add new textview dynamically.
      4. Everything is working fine.
      5. Ohh ok what kind of value does it need?
      6. but the array gets doubled in some places as in if the first value is 'dog' after few values another value called 'dog' comes.
      7. Thank You.
      Negative Reactions
      1. @Ruch1234 post a new question with relevant details.i am sure your problem can be solved.
      2. @Ruch1234 since this post already has a accepted answer it is not good to edit it further.
      3. Then the error comes again.
      4. But still the error message shows "Unfortunately the app is not responding".
      5. I check whether there is any errors and see if its not ok i will post a question.
      6. I get this now 12-24 11:07:04.802: W/dalvikvm(1848): threadid=1: thread exiting with uncaught exception (group=0x409961f8)12-24 11:07:04.822: E/AndroidRuntime(1848): FATAL EXCEPTION: main12-24 11:07:04.822: E/AndroidRuntime(1848): java.lang.NullPointerException: println needs a message12-24 11:07:04.822: E/AndroidRuntime(1848): at android.util.Log.println_native(Native Method)12-24 11:07:04.822: E/AndroidRuntime(1848): at android.util.Log.i(Log.java:159).
      7. New problem post a new Question.
      8. @Ruch1234 your Log needs a value since the value is null you get that exception.
      9. 12-24 11:07:04.822: E/AndroidRuntime(1848): at com.qrodsintegrated.QMFragment$TheTask.onPostExecute(QMFragment.java:122)12-24 11:07:04.822: E/AndroidRuntime(1848): at com.qrodsintegrated.QMFragment$TheTask.onPostExecute(QMFragment.java:1)12-24 11:07:04.822: E/AndroidRuntime(1848): at android.os.AsyncTask.finish(AsyncTask.java:602)12-24 11:07:04.822: E/AndroidRuntime(1848): at android.os.AsyncTask.access$600(AsyncTask.java:156)12-24 11:07:04.822: E/AndroidRuntime(1848): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615).
      Other Reactions
      1. but if its null you get NPE.
      2. I did it.
      3. Then update textview in onPostExecute.
      4. Make sure asynctask is an inner class of fragment.
      5. Ohh is that so.
      6. initialize it in onCreateView.
      7. @Ruch1234 you can declare textview as a instance variable.
      8. I'll do as you told me and get back with you.
      9. @Ruch1234 a string in your case ie the result of json.
      10. have text view in layout.
      11. So how to solve that ?

    2. Java Complex JSON parsing (variable fields)

      so that i can try. Try this way SAMPLE OUTPUT highlighting is not a child of responseHeader so I get right from the read json. details

      Reactions - Positive 2, Negative 4, Others 0

      1. JSONObject outerObject = new JSONObject(json)
      2. JSONObject innerObject = outerObject.getJSONObject("highlighting")
      3. for(Object key : innerObject.keySet()) { JSONObject o =innerObject.getJSONObject(key.toString())
      4. String[] elementNames = JSONObject.getNames(o)
      5. System.out.printf("%s >> %d ELEMENT(S) IN CURRENT OBJECT:\n", key, elementNames.length)
      6. for (String elementName : elementNames) { System.out.println(elementName)
      7. String value = o.get(elementName).toString()
      8. System.out.printf("name=%s, value=%s\n", elementName, value)
      9. } System.out.println()
      10. }

      Positive Reactions
      1. you are perfectly right, i removed it but now i am stuck with - Exception in thread "main" org.json.JSONException: JSONObject["highlighting"] not found.I am using the same json posted above....would appreciate advice ..thanks much.
      2. it says valid json, i think it is due to the recursive elements in the json, somehow the program cant handle that.
      Negative Reactions
      1. i downloaded the jar from the url you gave & it compiles now...however on execution, it gives below error Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1":{" ^.
      2. @Christudas The exception is not related to json I think.
      3. @Christudas Drop the following jar on your classpath: URL_http://repo1.maven.org/maven2/org/json/json/20131018/json-20131018.jar .
      4. This regex has a syntax error.
      Other Reactions
      1. @Christudas Check the loaded json on URL_http://jsonlint.com .
      2. @AjayThakur Why ?
      3. @Christudas Check the json again...
      4. @AjayThakur I use org.json.JSONObject.
      5. I tried that actually, it is valid jsonJSON as below -.
      6. It seems you're using a regexp.
      7. Check it.
      8. There is no method with keySet in JSONObject.
      9. Look at this: java.util.regex.PatternSyntaxException*.
      10. Change Method name from keySet() to keys() in outer for loop.
      11. It can be found here: URL_http://mvnrepository.com/artifact/org.json/json/20131018 .
      12. There is no reason why highlighting can't be found...

    3. Decoding JSON String in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // Creating a JSONObject from a String JSONObject nodeRoot = new JSONObject(sJSON)
      2. // Creating a sub-JSONObject from another JSONObjectJSONObject nodeStats = nodeRoot.getJSONObject("stat")
      3. // Getting the value of a attribute in a JSONObjectString sSDR = nodeStats.getString("sdr")

    4. Unchecked conversion

      I think returns an Iterator instance not an Iterator<String so you either leave the String away or just live with the warning . You can't avoid this warning because the android returns a raw Iterator. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject#keys()

    5. Exception when handling JSON

      You are trying to use JSONArray for a JSON Object. try . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = new JSONObject (result)

      Positive Reactions
      1. Thanks It works :).

    6. How to convert JSON string to custom object?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static MyClass convertFromJSONToMyClass(JSONObject json) { if (json == null) { return null
      2. } MyClass result = new MyClass()
      3. result.username = (String) json.get("username")
      4. result.name = (String) json.get("name")
      5. return result
      6. }

    7. Android Java - Get JSON Value

      I've tried the following:String upc jObj.getString("upc") Object aObj jObj.get("upc");JSONObject.get("upc");Get:11-24 11:08:01.120 W/System.err(1394) org.json.JSONException No value for upc. represents json object node represents json array node So use Another example So to get allergen_name . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject jObj = new JSONObject(data)
      2. String value = jObj.getString("upc")

      Positive Reactions
      1. I'm a PHP developer giving Java a shot for the first time and you have been more than helpful!.
      2. Thank you very much Raghunandan..

    8. check value exist or not in JSON object to avoid JSON exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject#isNull(str)

    9. check value exist or not in JSON object to avoid JSON exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject#has(key)

    10. check value exist or not in JSON object to avoid JSON exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject#optString(String key, String defaultValue)

    11. Quickest way to convert XML to JSON in Java

      before this Include Java-Json.jar in your library. hope this will Help. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String SoapmessageString = "yourSrtringURLorFILE"
      2. JSONObject soapDatainJsonObject = XML.toJSONObject(SoapmessageString)
      3. System.out.Println(soapDatainJsonObject)

    12. How to put JSON information in an array to use it for displaying in ListView

      Now from this array you can grab individual JSONObject for each object in your array. From the JSONObject you can now access your three values. details

      Reactions - Positive 6, Negative 1, Others 0

      1. JSONObject objectOne = new JSONObject(0)
      2. // Grabs your first item

      Positive Reactions
      1. Like one of the JSON array entry won't have the data label or any values there.
      2. Do you mean that your value is just an empty string after parsing the JSON?
      3. You can add a property to a json object by doing something like this: jsonObject.put("data", "some value"); And you could do this after checking the isNull I mentioned before.
      4. I would recommend using Androids AsyncTask to run your network call on a new thread.
      5. But like I said, this may be more than what you need for your application.
      6. jsonObject.isNull("data"); This will return true if there is no mapping for data.
      Negative Reactions
      1. So you can only try to grab a value for data if that returns false.
      Other Reactions
      1. Yeah that would be one approach to do it, if you are looking to expand on this and maybe persist the data you may want to look into storing your data in a database on the phone once you receive it.
      2. What if some of the entry is NO DATA, can I dummy fill it with data?
      3. You can use the isNull method available in the JSONObject to check if there is data there.
      4. I was able to receive the json text and now to extract it.
      5. Eclipse gives me a warning: 11-11 15:26:11.433: W/System.err(9054): org.json.JSONException: No value for dataI am wondering if the any of the label is missing, just fill it with dummy data.
      6. URL_http://developer.android.com/reference/android/os/AsyncTask.html .
      7. jsonString is which variable in my class?
      8. This would be the result you get back from your network call.
      9. Does that help?
      10. Here is my Pastebin: URL_http://pastebin.com/260jvLcx (I am opening up a chat for this).
      11. I have 7 entries but once it received a blank entry it skips everything after.
      12. Also all networking needs to be done on a separate thread and not the UI thread.
      13. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/40980/discussion-between-sikni8-and - dejanristic).
      14. If you look at my full program code, maybe you will have a better understanding of it?
      15. This way where ever you are in your app you could do a query to retrieve the data.
      16. I am thinking I can put it in a Public array which can be accessible by any of the fragments within the activity.
      17. Is there anyway to fill it with dummy, or it just won't be allowed to do that?

    13. Getting a JSON object from a target host. Error: Target host must not be null

      I think you're missing the http scheme so instead of put EDIT Even if that will work parsing of JSON will fail because of this line this assumes the response is an array but it's a JSONObject that contains two entries resultsCount and results. You need to make it a JSONObject . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = new JSONObject(data)

      Positive Reactions
      1. Thank you very much gunar!.

    14. Multiple values for a JSON key

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject()
      2. // Add a JSON Object JSONObject Record = new JSONObject()
      3. Record.put( "customer_name", "ABC")
      4. Record.put( "customer_type", "music")
      5. json.put( "RECORD", Record)
      6. // P toString() System.out.println( "JSON: " + json.toString() )

    15. Multiple values for a JSON key

      . Try like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject()
      2. jsonObject.put("customer_name", "ABC")
      3. jsonObject.put("customer_type", "music")
      4. JSONObject jsonObject_rec = new JSONObject()
      5. jsonObject_rec.put("RECORD", jsonObject)
      6. System.out.println(jsonObject_rec)

    16. How to deserialize only some fields in JSON?

      I could not find a way to do something this simple using Gson. You would just do . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String wantedName = new JSONObject(jsonString).getString("wantedName")

    17. Parse serialized json payload in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String payload = data..getJSONObject("xml-fragment").getJSONObject("payloadModel").getString("serializedPayload")
      2. JSONObject theRealData = new JSONObject(payload)

    18. Returning JsonObject using @ResponseBody in SpringMVC

      If you want to correctly write the JSON simply return a String. Or make your own HandlerMethodReturnValueHandler a little more complicated but more rewarding. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @RequestMapping("/test")@ResponseBodypublic String test() { JsonObject result = Json.createObjectBuilder() .add("name", "Dade") .add("age", 23) .add("married", false) .build()
      2. return result.toString()
      3. }

    19. java.lang.ClassCastException when reading the json file using java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. obj = parser.parse(sCurrentLine)
      2. String str = obj.toString()
      3. JSONObject jsonObject = new JSONObject(str)

    20. java.lang.ClassCastException when reading the json file using java

      I will follow your code. I had same issue to solve it replace this by . details

      Reactions - Positive 0, Negative 0, Others 0

      1. obj = parser.parse(sCurrentLine)
      2. JSONObject jsonObject = (JSONObject) obj

    21. How to parse JSON Array (Not Json Object) in Android

      use the following snippet to parse the JsonArray. Hope it helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < jsonarray.length()
      3. i++) { JSONObject jsonobject = jsonarray.getJSONObject(i)
      4. String name=jsonobject .getString("name")
      5. String Url=jsonobject .getString("url")
      6. }

    22. getting ' JSON EXCEPTION: no value for ' error?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. jsonObject = new JSONObject(json)

    23. Separate JSON string into variable in android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static String getString(JSONObject object, String tag, String defString) { if (object.has(tag)) return object.getString(tag)
      2. else return defString
      3. }

    24. Separate JSON string into variable in android

      Something like . You can use droidQuery to simplify your parsing . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object[] array = $.makeArray(jsonArr)
      2. for (Object obj : array){ Map<String, ?> map = $.map((JSONObject) obj)
      3. for (Map.Entry<String, ?> entry : map) { Log.d("DEBUG", String.format(Locale.US, "Object contains Key %s and value %s", entry.getKey(), entry.getValue().toString())
      4. }}

    25. nameValuePair key added in new JSONObject

      there are some disadvantages in using JSONStringer instead of toString() read it here . First of all your json is syntactically correct but I guess you wished to represent objects as values in your case the curly brackets are evaluated as simple strings using a json like this instead will produce values as objects Anyway I've tried to create that JSONObject and then print a toString of it and it will simply print the json without any accessory name. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String curStr = "{\"e\": {}, \"f\": {}, \"g\": {}}"
      2. JSONObject oldObj = new JSONObject(curStr)

    26. nameValuePair key added in new JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}"
      2. JSONObject oldObj = new JSONObject(curStr)

    27. Android: Exception when converting a String into a JSONObject

      The correct types of all the values in your JSON are On the other hand if your name was an embedded JSON object consisting of first middle and last names your JSON string ignoring the rest of the keys for brevity would have looked like Now we can put to use because we really do have an embedded JSON object. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject jsonObj = new JSONObject("{\"name\": {\"fname\" : \"An\", \"mname\" : \"der\", \"lname\" : \"Decke\"}}")
      2. // get embedded "name" JSONObjectJSONObject name = jsonObj.getJSONObject("name")
      3. System.out.println(name.getString("fname") + " " + name.getString("mname") + " " + name.getString("lname"))
      4. // An der Decke

      Positive Reactions
      1. I've added an example on when to use getJSONObject() as well.
      Other Reactions
      1. @user2708728, Yes.
      2. Ok, that means I have to treat each item dependent of it's type...thx.

    28. Android: Exception when converting a String into a JSONObject

      In this case it seems it is a String. It's as if you were doing which obviously makes no sense as they are incompatible types. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject value = (JSONObject) new String("asdasdsa")

    29. how to create jsonObject according this structure?

      You can also always go with JSON's official library . Use JSONObject Class from net.sf.json.JSONObject like this . details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject jsonObject=new JSONObject()
      2. JSONObject childObject=new JSONObject()
      3. childObject.put("class", "group")
      4. childObject.put("text", "test1")
      5. jsonObject.put("1", childObject)
      6. jsonObject.put("2", childObject)
      7. System.out.println(jsonObject.toString())

      Positive Reactions
      1. thanks ....
      Negative Reactions
      1. i wrote similar lines, but got errors childNode.put("class", element.className()); childNode.put("text", element.ownText()); group.put(i, childNode);becasue "i" is a integer, how to fix it?
      Other Reactions
      1. fixed.

    30. combine two Map String into JSON

      thanks. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject object = new JSONObject(map1)
      2. object.put('selection', map2)
      3. System.out.println(object.toString())

      Positive Reactions
      1. Thanks, it is solved!
      Other Reactions
      1. you are right, using JSONObject.

    31. Simple json like this. creating and parsing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. timeArray.put(new JSONObject().put("Admin", "CreateUser"))
      2. System.out.println(timeArray)
      3. // prints: [{"UserId":"Action"},{"UserId":"Action"},{"Admin":"CreateUser"}]

    32. Simple json like this. creating and parsing

      "timestamp1":["id","action"],"timestamp2":["id","action"]. Yes it's possible just use this to create and to parse but I don't recommends you to create JSON with format like that the JSONObject property key must be unique I suggest you to use JSONArray instead of JSONObject I hope this can help you . details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject obj=new JSONObject()
      2. JSONObject timeObj = new JSONObject()
      3. timeObj.put("UserId", "Action")
      4. obj.put("time", timeObj)

      Positive Reactions
      1. thanks, keys are not actually duplicate.
      Negative Reactions
      1. sorry.

    33. Simple json like this. creating and parsing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object obj=JSONValue.parse(value)
      2. JSONObject object=(JSONObject)obj
      3. JSONObject timeObj = obj.get("time")
      4. String action = timeObj.get("UserId")

    34. JSON jsonObject.optString() returns String "null"

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private String optString_1(final JSONObject json, final String key) { return json.isNull(key) ? null : json.optString(key)
      2. }

    35. parse json rest response in java

      I just extracted mother name from data. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject data = (JSONObject) jsonObject.get("data")
      2. final String motherName = (String) data.get("MOTHERS_NAME")

      Positive Reactions
      1. Thank you Shamim,.

    36. get JSON object from a HTTP response

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObj = new JSONObject("yourJsonString")

    37. get JSON object from a HTTP response

      It means that you get the JSON object but in a String format. If you are supposed to get a JSON Object you can just put . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject myObject = new JSONObject(result)

    38. Jackson API: partially update a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. -- AVERAGE ----------------------------------------------------------------------------| 1| 860,560| 157,772| 234,654| 1,595,018| 488,427|---------------------------------------------------------------------------------------| | RO JSONObject| RO Jackson| R/- Jackson| R/W JSONObject| R/W Jackson|---------------------------------------------------------------------------------------

    39. How to serialize OBJECT ARRAY in java?

      Overview of JSON API's for Java here . requires JSONObject . details

      Reactions - Positive 0, Negative 1, Others 0

      1. new JSONObject(parameters).toString().getBytes()

      Negative Reactions
      1. i have this error message: The constructor JSONObject(Object[]) is undefined, any idea?
      Other Reactions
      1. However, there's no guarantee it will work---it all depends on what the framework can do with your array elements.
      2. nope, nothing changed.
      3. Clearly, you need a JSONArray if you're going to serialize an array.

    40. How to convert json objects with number as field key in Java?

      Because the key is useless here I only need the value set so I iterate the set to extract the value set. If you have more complex structure like nested json objects you can have something like this Hope it helps. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (Entry<String,JsonElement> j : locations) { JsonObject location = (JsonObject) j.getValue()
      2. JsonObject coordinate = (JsonObject) location.get("coordinates")
      3. JsonObject address = (JsonObject) location.get("address")
      4. System.out.println(location.get("location_id"))
      5. System.out.println(location.get("store_name"))
      6. System.out.println(coordinate.get("latitude"))
      7. System.out.println(coordinate.get("longitude"))
      8. System.out.println(address.get("street_number"))
      9. System.out.println(address.get("street_name"))
      10. System.out.println(address.get("suburb"))
      11. }

    41. How to convert json objects with number as field key in Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (Entry<String,JsonElement> j : set) { JsonObject value = (JsonObject) j.getValue()
      2. System.out.println(value.get("id"))
      3. System.out.println(value.get("value"))
      4. }

    42. How to convert hash of hashmaps to json in java

      do "validations":{"compulsary":1},"label":"I am working on something" . use Other functions you can get from its documentation . details

      Reactions - Positive 0, Negative 0, Others 0

      1. new JSONObject(map)

    43. Getting data from database tables

      yes exactly . I don't think that the JSONArray object has a function but you can make one yourself See this link for an value example . details

      Reactions - Positive 5, Negative 0, Others 0

      1. contains(JSONObject obj)

      Positive Reactions
      1. scout please cud u please clarify me on this...am new to json.
      2. yeah scout tanx for de help...but i av resolved dis....i jst changed my query in de repository class....i used select distinct kedv.denomination..............nd it worked.
      3. no please..it ddnt work.
      4. okay, sounds good.
      5. Please make an edit with in your question with your entire code.
      Other Reactions
      1. ?
      2. I looks about right, but in this function you have surrounded denomination with quotes.
      3. Try this: getDenominationByType() method....public boolean denominationExists(JSONArray theJSONArray, BigDecimal denomination) { return theJSONArray.toString().contains("\" \":"+denomination); }.
      4. In your json above there are not quotes around the denomination.
      5. Did this work?
      6. aryt will try this nd let u knw de outcome.
      7. plss make a suggestion.
      8. URL_http://stackoverflow.com/questions/17735660/how-to-set-limit-for-a-hibernate - query/17735918?noredirect=1#17735918.
      9. Does this work?
      10. hi scout...i created this method and call it my getDenominationByType() method....public boolean denominationExists(JSONArray theJSONArray, BigDecimal denomination) { return theJSONArray.toString().contains("\" \":\""+denomination+"\""); }.

    44. Sending JSON as HTTP POST parameter (Android/Java)

      I'm not sure what StringEntity really does but when I was developing a simple REST API PHP at the other end I never used it Also see this Q&A on a similar problem httppost-call-with-json-encoded-body). I gave this up and decided to go the dirty-way replacing chars manually the following way It's ugly probably dangerous or risky but it works . details

      Reactions - Positive 0, Negative 0, Others 0

      1. json = new JSONObject(nameValuePairs.toString().replace("\"", "'"))
      2. json = new JSONObject(json.toString().replace("\"", ""))

    45. Adding TestCaseSteps to TestCases using Rally Rest for Java

      In this case rather than trying to add items to the Steps array of the TestCase instead simply create your TestCaseStep objects and specify the TestCase's ref as the TestCase value to link them. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JsonObject stepOne = new JsonObject()
      2. stepOne.addProperty("Input", "Push Button")
      3. stepOne.addProperty("ExpectedResult", "Light Show")
      4. stepOne.addProperty("TestCase", "/testcase/12345")
      5. //specify test case object id in place of 12345CreateRequest createStepRequest = new CreateRequest("testcasestep", stepOne)
      6. rest.create(createStepRequest)

      Positive Reactions
      1. Thanks dude I appreciate the helpful answer.

    46. HTTPResponse as JSON in Java

      The sample code. For details information go through to the link. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonReader reader = Json.createReader(new URI(url, true))
      2. JsonObject jsonObject=reader.readObject()

    47. How to make a JSON String using the key/value from the Map

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.JSONObject
      2. JSONObject rootJo = new JSONObject()
      3. for (AttributeValue<?> al : list) { JSONObject mapJo = new JSONObject(al.getValue())
      4. rootJo.put("v", mapJo)
      5. }

    48. How to make a JSON String using the key/value from the Map

      Not sure what exact task you're working but there are many JSON libraries for Java which can do this for you such as json-in java and google-gson . For example in json in java once you have filled all the values in its JSONObject then converting it into JSON string is fairly easy For example in your case you may create a JSONObject like the following and invoke its toString function. details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject.toString()
      2. // compact JSON stringJSONObject.toString(int indent)
      3. // easier readable format with indention.

      Positive Reactions
      1. This should be extremely straightforward and should not involve any of the headaches involved with manually constructing a JSON string.
      Negative Reactions
      1. The OP is making this WAY too complicated.
      Other Reactions
      1. Meaning, I need to append those, lv and v in my actual JSONString.
      2. If you create the right json object, then it will certainly generate the right output for you ...
      3. I'm on the same page as you are @keelar.
      4. @user21973: I don't understand.
      5. I can use various JSON libraries but those won't give me lv and v in the way I am looking in my actual JSONString.

    49. How to make a JSON String using the key/value from the Map

      For example in json in java once you have filled all the values in its JSONObject then converting it into JSON string is fairly easy For example in your case you may create a JSONObject like the following and invoke its toString function. This can safe your time from formatting string to fit the JSON format and here is its output . details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject jsonObject = new JSONObject()
      2. Map<String, String> strStrMap = new HashMap<String, String>()
      3. strStrMap.put("hello", "world")
      4. strStrMap.put("here is", "an example")
      5. jsonObject.put("myMap", strStrMap)
      6. System.out.println(jsonObject.toString(2))

      Positive Reactions
      1. This should be extremely straightforward and should not involve any of the headaches involved with manually constructing a JSON string.
      Negative Reactions
      1. The OP is making this WAY too complicated.
      Other Reactions
      1. Meaning, I need to append those, lv and v in my actual JSONString.
      2. If you create the right json object, then it will certainly generate the right output for you ...
      3. I'm on the same page as you are @keelar.
      4. @user21973: I don't understand.
      5. I can use various JSON libraries but those won't give me lv and v in the way I am looking in my actual JSONString.

    50. Trouble parsing through complicated json

      To iterate through the times in the array simply loop over it and pull out each JSONObject. For example . details

      Reactions - Positive 1, Negative 0, Others 0

      1. for(int i = 0
      2. i < weatherObservationItems.length()
      3. i++) { JSONObject item = weatherObservationItems.getJSONIbject(i)
      4. String name = item.getString("name")
      5. String desc = item.getString("description")
      6. // etc etc}

      Positive Reactions
      1. Hope it makes sense.
      Other Reactions
      1. if I do data, how do I cylce through all the results?
      2. @Mike I've updated the answer with a sample of looping through the JSONArray and getting some of the data in the results.

    51. Trouble parsing through complicated json

      The error is telling you that there is no value for JSON. This is because of this line Basically you need to use the propery key when selecting a property from the JSON object. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject weatherObservationItems = new JSONObject(jsonObject.getString("JSON"))

      Positive Reactions
      1. Hope it makes sense.
      Other Reactions
      1. if I do data, how do I cylce through all the results?
      2. @Mike I've updated the answer with a sample of looping through the JSONArray and getting some of the data in the results.

    52. Accessing JSON property name using java

      Or am I doing this completely assbackwards right from the get go. In the JSON.org reference implementation you could do In JSON simple you would do This should do the trick. details

      Reactions - Positive 0, Negative 4, Others 0

      1. for (String key : JSONObject.getNames(jsonObject)){ map.put(key, jsonObject.get(key))
      2. }

      Negative Reactions
      1. No worries perhaps I'm using the wrong name for that library, I'll review and update if needed.
      2. My bad, I thought that would refer to the "simple" reference implementation of json.org.
      3. I think that did the trick.
      4. As you can see in the code I posted, it is a static method of the JSONObject class.
      Other Reactions
      1. I'm getting "The method getNames(JSONObject) is undefined for the type JSONObject" when I use this code for my project.
      2. Allow me to edit my answer.
      3. Where is getNames coming from?
      4. It's now only saving the last line of the file in the parent list, but I dont' think it's related to this issue.
      5. Are you using the same library?
      6. Okay, try my edit.

    53. simplest way to read json from a URL in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String url = "your url"
      2. JSONParser jsonParser = new JSONParser()
      3. JSONObject object = jsonParser.getJSONFromUrl(url)
      4. String content=object.getString("json key")

    54. saving json data in hdfs in hadoop

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static class TokenCounterReducer extends Reducer<Text, Text, Text, NullWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for (Text value : values) { JSONObject jsn = new JSONObject()
      2. .... context.write(new Text(jsn.toString()), null)
      3. } }}

    55. JSON response is returning as text

      But I have created a sample Servlet and it returned the Json output with the same above code. And I got "Message":"Client unauthorized","Response":"1" as output on the browser. details

      Reactions - Positive 0, Negative 0, Others 0

      1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("application/json
      2. charset=UTF-8")
      3. PrintWriter printout = response.getWriter()
      4. JSONObject JObject = new JSONObject()
      5. JObject.put("Response", "1")
      6. JObject.put("Message", "Client unauthorized")
      7. printout.print(JObject)
      8. printout.flush()
      9. // Or // printout.write(JObject.toString())
      10. }

    56. Parsing json object into a string

      KwintenP Try using the json-smart library . You can then simply retrieve the JSON object first using What's more you can retrieve a specific object inside a JSON object may it be another object an array and convert it to a String or manipulate the way you want. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject test = (JSONObject) JSONValue.parse(yourJSONObject)
      2. String TestString = test.toString()

    57. What am I doing wrong in this parsing?

      You are trying to get the element children as a JsonObject but it is a JsonArray because it is surrounded by . Try something like this Note I assume that you only want to get the data of the first element of the children array since it seems that it is what you want looking at your code and mainly looking at how-do-i-use-googles-gson-to-get-a-certain-value-from-a-json-response this other-question-of-yours . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser parser = new JsonParser()
      2. JsonObject rootObj = parser.parse(json).getAsJsonObject()
      3. //Here is the changeJsonObject locObj = rootObj .getAsJsonObject("data") .getAsJsonArray("children") .get(0) .getAsJsonObject() .getAsJsonObject("data")
      4. String subreddit = locObj.get("subreddit").getAsString()

    58. Decoding JSON String in Java

      Better you check this . This is the best and easiest code The library-definition-of-the-json-files-are-given here . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class test {
      2. public static void main(String str[]) {
      3. String jsonString =
      4. "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}"
      5. JSONObject jsonObject = new JSONObject(jsonString)
      6. JSONObject newJSON = jsonObject.getJSONObject("stat")
      7. System.out.println(newJSON.toString())
      8. jsonObject = new JSONObject(newJSON.toString())
      9. System.out.println(jsonObject.getString("rcv"))
      10. System.out.println(jsonObject.getJSONArray("argv"))
      11. }
      12. }

    59. JSONArray cannot be converted to JSONObject given a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObj = new JSONObject(new String(blah))

    60. Processing shell-style comments in JSON

      I know I can hack a solution with RegEx etc but I'd prefer to find out if there are libraries which support this. What I chose to do is modify the public domain JSON.org library to support shell comments and adding comments to the JSON object as I've done in this GitHub gist Example of use Example output. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj=new JSONObject("{ # Comment\n"+ "\"first-key\":\"first-value\",\n"+ "\"second-key\":\"second-value\" }", JSONObject.OPTION_SHELL_COMMENTS | // Support SHELL-style comments JSONObject.OPTION_ADD_COMMENTS // Incorporate comments in the JSON object)
      2. System.out.println(obj)
      3. // Output the JSON object

      Positive Reactions
      1. I will make this clear with further examples.
      Other Reactions
      1. Can you tell me if this solution is working for you?
      2. I'm still considering all my options, and considering changing the interchange format outright.
      3. The current implementation coalesces comments that occur right next to each other, but not comments that occur in different places within the same sub- object.
      4. Just to check if I'm understanding: this only allows one comment per object?
      5. If I go ahead with this solution, I'll give you the green tick.

    61. Best Way to Parse JSONObjects and JSONArrays

      It's part of the standard Android distribution. The code can be as simple as Then you just need to navigate the object structure of thing to get to the data you need. details

      Reactions - Positive 4, Negative 8, Others 0

      1. JSONObject thing = new JSONObject(jsonString)

      Positive Reactions
      1. It looks like the output from your Log.e() calls.
      2. Thanks again Ted.
      3. Do you mean something like this try { //JSONObject jobj2 new JSONObject(builder.toString()); return new JSONObject(builder.toString()); //jarray jobj2.getJSONObject("summary"); } catch (JSONException e) { } // return JSON String return jobj2;.
      4. Thanks for the answer, i've got a JSONParser activity im using, i've posted above.
      Negative Reactions
      1. The exception is coming from onPostExecute, so it looks like your JSON parsing code is completing normally and there's another problem later.
      2. If it throws an exception, you can return null, an empty JSONObject, or exit the method with an exception.
      3. I've fixed the issue - ill update the code above.
      4. @JaisonBrooksDevelopment - Are those actually errors?
      5. You might want to change them to be Log.i() so that they appear as information lines in the log instead of error lines.
      6. Have you tried simply return new JSONObject(builder.toString());' in the try block?
      7. It all depends on how you want to handle errors in the calling code.
      8. @JaisonBrooksDevelopment - I mean that the try block should be one statement: return new JSONObject(builder.toString());.
      Other Reactions
      1. Why can't you parse the object?
      2. i've place some updated code above and my current logcat issues - you mind double checking to make sure i understand you fully.
      3. The issue im having now is im not able to Parse the JSONObject with the 2nd part of my JSONParser activity using getJSONFromUrl2 instead of getJSONFromUrl.
      4. @JaisonBrooksDevelopment - I suggest that you mark this question as solved and start a new question regarding the log output.
      5. @JaisonBrooksDevelopment - I don't know where that log line is coming from.
      6. @JaisonBrooksDevelopment - While waiting for your update, I posted some sample code of my own.
      7. Your's looks okay.
      8. Thanks for the recommendation, should i be concerned how many times they are repeating does this mean that section of my code is being executed this many time before it actually get the final data.
      9. @JaisonBrooksDevelopment - You seem to have commented out the code that does the parsing.
      10. However in my stack im getting some weird output in the log.
      11. My guess is the suspicious-looking log line in the doInBackground loop where you are calling Log.e("JSON Parser", summary + args.toString()); It looks like summary and args don't change, so you get the same log entry each time through the loop.

    62. How can the datatype of a JSON property be determined?

      Parse it into a Map retrieve the item as an Object and test its class. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject stuff = new JSONObject(whatever)
      2. Object thing = stuff.get("key")
      3. String classNameOfThing = thing.getClass().getName()
      4. Systen.out.println("thing is a " + classNameOfThing)
      5. if (thing instanceof Integer) { System.out.println("thing is an Integer")
      6. }

      Positive Reactions
      1. perfect.
      2. thanks.

    63. JSON array is not being created from a stream

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. jsonArray = new JSONObject(stream)

    64. JSON array is not being created from a stream

      ALWAYS look at the exception message when debugging Java. Because it's not a json array its a json object starts with ) . details

      Reactions - Positive 1, Negative 0, Others 0

      1. jsonobject = new JSONObject(stream)

      Positive Reactions
      1. nice one tys ...
      Other Reactions
      1. Gee, where do you find objectys?

    65. How to check the type of a value from a JSONObject?

      If you want more control over JSON parsing use some other parser than org.json such as Jackson. You could do something like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jString = "{\"a\": 1, \"b\": \"str\"}"
      2. JSONObject jObj = new JSONObject(jString)
      3. Object aObj = jObj.get("a")
      4. if(aObj instanceof Integer){ System.out.println(aObj)
      5. }

    66. How to check the type of a value from a JSONObject?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.get()

    67. How to convert String to JSONObject in Java

      Thanks to all guys. If you are using lib.sourceforge.net net.sf.json.JSONObject it is pretty easy or get the values then withjson.getString(param) json.getInt(param and so on. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String myJsonString
      2. JSONObject json = JSONObject.fromObject(myJsonString)

      Positive Reactions
      1. JSONObject json JSONSerializer.toJSON(myJsonString); will produce an erroe of Type mismatch the other one works.

    68. How to convert String to JSONObject in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = JSONSerializer.toJSON(myJsonString)

    69. Handling null values when parsing JSON data

      This is my source code I hope somebody can help me to solve this problem thanks. You can do something like . details

      Reactions - Positive 4, Negative 1, Others 0

      1. JSONObject c = jsonArray.getJSONObject(i)
      2. if (c.has("atasan")) map.put("atasan", c.get("atasan").toString())
      3. if (c.has("nama_agen")) map.put("nama_agen", c.get("nama_agen").toString())

      Positive Reactions
      1. thank u very much.
      2. i will noted it, thank u very much....
      3. it works...!
      4. In order to keep the JSON structure consistent, I'd recommend to put JSONObject.Null rather than skipping fields from the object.
      Negative Reactions
      1. And just to explain a little bit why this must work, consider:map.put("kode_agen", c.get("kode_agen").toString());If c.get("kode_agen") returns null, you'll wind up with a NullPointerException.
      Other Reactions
      1. Always check before using, hence has()..

    70. How to retrieve JSON data inside an JSON object?

      I've fixed the code. Do following code them use SimpleDateFormat to parse time string and get date object . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONOject origin = (JSONObject) jsonObj.get("Origin")
      2. String time = (String) origin.getString("time")

    71. How to retrieve JSON data inside an JSON object?

      perhaps you'd like to use date to parse it. Since Time is part of the Origin"-object you would need to extract the Origin"-object first And then . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONOject origin = (JSONObject) jsonObj.get("Origin")

    72. How to convert HashMap to json Array in android?

      ThrowsNullPointerException if any of the map's keys are null. Basic usage get the json array from the JSONObject Edit ok I'll show . details

      Reactions - Positive 5, Negative 0, Others 0

      1. JSONObject obj=new JSONObject(yourmap)

      Positive Reactions
      1. @Pragnani: Thanks!!!
      2. I can only hope it's tested - showing input and what it produces (at each stage) would make this an acceptable answer.
      3. Could you please paste code here?
      4. It Works for me...
      5. Happy to get the reply from you brother..I was always your fan.
      Other Reactions
      1. I have no idea by what logic that is supposed to work.
      2. @pst is it ok now.
      3. @K That is not JSONObject, that is just a String obj.toString() returns string.
      4. @Sandeep I have updated check once.
      5. I have tried but didn't work.

    73. How to make directory structure from array of JSON objects

      I have to convert this JSONArray into another JSONArray where I can have elements nested inside their parent(directory like structure like Can anybody help me here what is the best possible way to do so. You'll have something like this pseudo code I apologize in advance for not being more specific but this should work pretty generically for whatever you want to do. details

      Reactions - Positive 2, Negative 0, Others 0

      1. // Element is { id, children }Dictionary<String, Element> elements
      2. for (JSONObject obj : arr) { if (elements.hasKey(obj.id)) { // Maybe you need to update your element or something here } else { // Create your element elements[obj.id] = new Element(obj.id)
      3. } // if the parent does not exist, create a shadow of the parent // (it'll get filled in with more info above if encountered later) if (!elements.hasKey(obj.parent)) { elements[obj.parent] = new Element(obj.parent)
      4. } // Add yourself to children elements[obj.parent].children.push(elements[obj.id])
      5. }// TODO: iterate your dictionary and put it into an array, this should be straightforward// Or if you want the root of your tree return elements[""]

      Positive Reactions
      1. The children may be nested up to n levels (parent>children>grand children and so on...).
      2. Thank you Anthony but your answer will work only if there is one level (parent>children) inside the hierarchy.
      Other Reactions
      1. This _should_ work approximately as posted.
      2. @rahul0789: Since I don't have a way of showing it in java, here's a javascript proof of concept: URL_http://jsfiddle.net/Ngd9H/1/ .
      3. I'll have to check my c# implementation of this when I get home (I needed to do the exact same thing except mine was folding a tree from a database).
      4. elements[""] should contain the root, which will have children that point at the other elements inside elements.

    74. Error parsing JSON Array, DOCTYPE

      It means that you download HTML data instead of JSON. For simple test you can try next code and you will get the same error You can get this wrong response from numerous reasons wrong request your fire wall proxy even server might return wrong result if you don't specify User-Agent header or doesn't perform authorization. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject object = new JSONObject("<!DOCTYPE html>")

    75. Android Json and null values

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject("{\"hello\":null}")
      2. json.getString("hello")

    76. How to avoid quotes around string values while creating JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj= new JSONObject()
      2. String title = "gro"
      3. String startExpr = "/.*"
      4. String endExpr = ".*/"
      5. obj.put("title", startExpr + title + endExpr )

    77. Android Json and null values

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. if (data instanceof Integer || data instanceof Double || data instanceof Long) { // handle number
      2. } else if (data instanceof String) { // hanle string
      3. } else if (data == JSONObject.NULL) { // hanle null
      4. }

    78. java android - iterate JSON objects in array

      When you later return it from the method its null. Unless you are trying to avoid re-parsing the JSON repeatedly I would advise getting rid of the class variables altogether. details

      Reactions - Positive 3, Negative 1, Others 0

      1. public class EnvConfig { private String rawJSONString
      2. private JSONObject jsonObjRecv
      3. // <-- you declare a class variable here // ... try { JSONObject jsonObjRecv = new JSONObject(rawJSONString)
      4. // <-- shadowed here!

      Positive Reactions
      1. thanks!
      2. ahhhh i see that now.
      3. Thanks for the enlightenment!.
      Negative Reactions
      1. i've never even heard of instance shadowing.

    79. Update elements in a JSONObject

      thanks man. Remove key and then add again the modified key value pair as shown below I haven't used your example but conceptually its same. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject js = new JSONObject()
      2. js.put("name", "rai")
      3. js.remove("name")
      4. js.put("name", "abc")

    80. Update elements in a JSONObject

      Like below . Use the put method ut%28java.lang.String,%20java.lang.Object%29 json/JSONObject.html#put%28java.lang.String,%20java.lang.Object%29 . details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person")
      2. person.put("name", "Sammie")

      Positive Reactions
      1. so simple!
      2. Ag, nice!
      3. thanks man.

    81. How to create a JSONArray that contains Javascript code inside Java?

      Thank you!. Another method would be create an array with just the coordinates and then in javascript . details

      Reactions - Positive 5, Negative 2, Others 0

      1. for(Place place: places){ JSONObject obj = new JSONObject()
      2. obj.put("lat",place.getContactData().getLatitude())
      3. obj.put("lng",place.getContactData().getLongitude())
      4. locations.put(obj)
      5. }

      Positive Reactions
      1. @Lester: There is not enough information to answer this question.
      2. :)Thanks a lot for all replies!.
      3. Now it works perfectly.
      4. Note that if you get the output [object Object],[object Object], that's perfectly normal.
      5. Sounds really smart.
      Negative Reactions
      1. What might I have missed?
      2. In the source code the array shows up as var places [{ "lng":9.963569641113281,"lat":53.56079864501953},{"lng":9.979949951171875,"lat ":53.55149841308594}]; but when I alert(places) it is empty.
      Other Reactions
      1. Maybe you call alert(places) where places is not visible.
      2. Maybe just some browser cache issue.

    82. How to retrieve items from database using JSONArray

      Otherwise you're just replacing the fields for the old object and adding another reference to it to the results. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. while(rs.next()){ //new line: JSONObject Obj = new JSONObject()
      2. // original part looks fine: Obj.put("uname",rs.getString("uname").trim())
      3. Obj.put("comment",rs.getString("comments").trim())
      4. CommArray.add(Obj)
      5. }

      Positive Reactions
      1. good catch.
      Other Reactions
      1. yup that is ur solution.

    83. Pass json object to a play-framework action

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void update(JsonObject body) { try { Long id = (long) body.get("id").getAsInt()
      2. CaseFolder cf = CaseFolder.loadAndVerifyOwner(getConnectedUser(), id)
      3. cf.number = body.get("number").getAsString()
      4. cf.description = body.get("description").getAsString()
      5. if(cf.validateAndSave()) ok()
      6. else error()
      7. } catch (NullIdException e) {error()
      8. } catch (NotFoundException e) {notFound()
      9. } catch (NotOwnerException e) {forbidden()
      10. } catch (Exception e) {e.printStackTrace()
      11. error()
      12. }}

    84. How separate keys and values in this JSON object, using Java?

      You may try this. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String s = " { "projector":"no", "video_conference":"no", "polycom":"no", "lcd":"no", "digital_phone":"no", "speaker_phone":"no" }"
      2. JSONObject jObject = new JSONObject(s)
      3. JSONObject menu = jObject.getJSONObject("projector")
      4. Iterator iter = menu.keys()
      5. String[] keyArr = new String()
      6. String[] valArr = new String()
      7. int count = 0
      8. while(iter.hasNext()){ keyArr[count] = (String)iter.next()
      9. valArr[count] = menu.getString(key)
      10. count +=1
      11. }

    85. JSONObject in JSONObject

      To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like . from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt method for getting integer value and use getString method for getting String value. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject mJsonObject = new JSONObject(response)
      2. JSONObject userJObject = mJsonObject.getJSONObject("user")
      3. JSONObject statusJObject = userJObject.getJSONObject("status")
      4. String stat1 = statusJObject.getInt("stat1")
      5. String stats2 = statusJObject.getInt("stats2")

    86. Java json object call function by name

      I ended up answering my own question. The solution is to use a JSONLiteral like so Java JS. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONObject getOptions() { JSONObject json = new JSONObject()
      2. json.put("fnRowCallback", new JSONLiteral(String.format("fnRowCallback()")))
      3. return json
      4. }

    87. How to send and receive JSON data from a restful webservice using Jersey API

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ClientConfig config = new DefaultClientConfig()
      2. Client client = Client.create(config)
      3. client.addFilter(new LoggingFilter())
      4. WebResource service = client.resource(getBaseURI())
      5. JSONObject inputJsonObj = new JSONObject()
      6. inputJsonObj.put("input", "Value")
      7. System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj))

    88. LoginTask(AsyncTask) NullPointer

      I guess it return null in json. Check in this line and you are accessing jsonResult which contain null. details

      Reactions - Positive 3, Negative 5, Others 0

      1. JSONObject json = jsonParser.getJSONFromUrl(loginVehicleURL, params)

      Positive Reactions
      1. BUT if i add the code in the btnLogin_OnClick 'String uname inputUserId.getText().toString(); String password inputPassword.getText().toString(); UserFunctions vehicleFunction new UserFunctions(); jsonResult vehicleFunction.loginVehicle(uname, password); ' and add 'StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);' into OnCreate, i can get the json successful.
      2. Here now you using the strict mode then its allows to do network operation and getting correct json.
      3. URL_https://lh5.googleusercontent.com/-BSHvYT9kddQ/UQVT-1pXsCI/AAAAA AAAB-k/V-couGmG6rs/s1198/2.JPG URL_https://lh3.googleusercontent.com/-yRjP04toN24 /UQVT-4nfr0I/AAAAAAAAB-o/vkSYxO2EE5o/s1226/1.JPG.
      Negative Reactions
      1. if i enable strict mode and do it in asyncTask, still return nullpointer.
      2. the problem is If i get json in async class, it will return null whether i add strict mode or not, but if i pull it into main thread, i get the json.
      3. and i want to solve the problem how to get the json in async class not return null json to me.
      4. if i want to test can i get the json return, i need to enable the strict mode because of android>=3.0.
      5. Another way to get json in async class then there is no need to write 'StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);'.
      Other Reactions
      1. and i get the result is yes.
      2. Its because i think you are running application android>=3.0.
      3. i can get the return json, not nulli need to complete asynctask, because i need run this app>=android3.
      4. Its always better to do network operation in asynchronous class.
      5. If you do network operation on main thread android>=3.0 which is now allow so its giving null in json.
      6. if i put it into btnLogin_onclick, i get can the return json.anyway thx again.

    89. Keep the order of the JSON keys during JSON conversion to CSV

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONObject(Map paramMap) { this.map = (paramMap == null ? new HashMap() : paramMap)
      2. }

    90. Efficient way of downloading data in Android App from MySQL

      You could have a class like this p.s. I'm writing all this without testing there will be a little mistake here in there but you'll get the idea) then on your protected Map doInBackground(String urls you complete the network operation create the JsonArray create a Map<String,CompanyData loop through the array creating CompanyData objects and placing them into the Map and return the map to your and inside the post execute it's just pass this result to the UI. details

      Reactions - Positive 7, Negative 0, Others 0

      1. public class CompanyData{ private String name, address, phone
      2. private int size
      3. public CompanyData(JsonObject jo){ name = jo.getString("name")
      4. address = jo.getString("address")
      5. phone = jo.getString("phone")
      6. size = jo.getInt("size")
      7. } // put a bunch of get methods here... // getName(), getAddress(), etc. }

      Positive Reactions
      1. The main idea on what I suggested is that you completely off-load the UI, so even if it takes the same time, this time will be taken on a background thread and your UI will keep running fast and smooth.
      2. thanks for the comment!
      3. Although I dont directly see any speed difference I get your point of doing all this work in the background.So I implemented the json parsing in the doInBackground like you suggested.But the download progress is fine then?
      4. Everything is working fine.
      5. The app works fine btw but I just thought that there were improvements in the downloading and parsing phase.
      6. Im going look in to this now and let you know if everything worked!
      7. depending on what platform you're targeting you can change to HttpURLConnection instead of HttpClient, as I've heard is more efficient, but you have to Google for details on it.
      Other Reactions
      1. The whole stream->String->Json part is that the way of doing and I've never seen a better way.
      2. :-).

    91. JSON_encoded String to Java JSONObject

      For more help on the matter you need to change the private JSON data to something which produces the same result as what you're experiencing when the JSON is validated by one of these sites otherwise there's not a lot we can do to help try and validate it . Found a nice solution using the parser serialized-php-parser lib After the serialization the JSON object can be parset like a charm. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(response)
      2. String theNonReadableJson = jsonObject.getString("key")
      3. SerializedPhpParser serializedPhpParser = new SerializedPhpParser( theNonReadableJson)
      4. Object serializedObject = serializedPhpParser.parse()
      5. JSONObject readableJson = new JSONObject(serializedObject.toString())

    92. Java XStream with HashMap

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsobj = new JSONObject(map)
      2. String strJson = jsobj.toString()

    93. Mapping JSON back to POJO with JSON and Jackson libs

      You need to have a class PojoClass which contains has-a Widget instance called fruit. Try this in your mapper This is your Widget Class. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{\"fruit\": {\"weight\":\"29.01\", \"texture\":null}, \"status\":\"ok\"}"
      2. JSONObject jsonObj = JSONObject.fromObject(str)
      3. try { // Contains the above string ObjectMapper mapper = new ObjectMapper()
      4. PojoClass p = mapper.readValue(jsonObj.toString(), new TypeReference<PojoClass>() { })
      5. System.out.println("w.weight = " + p.getFruit().getWeight())
      6. } catch (Throwable throwable) { System.out.println(throwable.getMessage())
      7. }

    94. how to add Json header in json array parsed from Java Object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject parent = new JSONObject()
      2. JSONObject subparentone = new JSONObject()
      3. JSONObject subparenttwo = new JSONObject()
      4. subparentone.put("child-1", "1")
      5. subparentone.put("child-2", "2")
      6. subparenttwo.put("child-2", "3")
      7. parent.put("sub-parent-1", subparentone)
      8. parent.put("sub-parent-2", subparenttwo)
      9. JSONObject finalparent = new JSONObject()
      10. finalparent.put("parent", parent)

    95. JSON add to JSONArray issue

      Id be grateful if anyone can help me here. You need to create a new jsonObj reference with every iteration of the loop Otherwise you are updating the same instance over and over again and adding a reference to the same object many times to the array. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int j = 0
      2. j < X.size()
      3. j++) { zBean aBean = (zBean)X.get(j)
      4. jsonObj = new JSONObject()
      5. //^^^^^^^^^^^^^^^^^^^^^^^^^^^ add this line jsonObj.put(ID,newInteger(aBean.getId()))
      6. jsonObj.put(NAME,aBean.getName())
      7. jsonArray.add(jsonObj)
      8. }

      Other Reactions
      1. Thanks a lot man, it solved my problem.

    96. What is the most suitable Java data structure for representing JSON?

      For that you can use Using these I read through my JSON array from my POST request and store the resulting information in Class objects in my project. For each item in JSONArray you can extract the JSONObject and attributes like this As far as actually storing the data like mentioned above JSON data can come in a wide array of formats depending on the source and as such it is usually parsed on the client end and saved in your application Class objects for use. details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < jsonArray.length()
      3. i++) { JSONObject jsonObject = jsonArray.getJSONObject(i)
      4. jsonObject.getString("text")
      5. }

    97. json and null value

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json_data = jArray.getJSONObject(0)
      2. if (json_data.opt("returnDate") == null) {}

    98. parsing of string into json in android

      Update your below code line it will solve your problem. or you can write below code instead of your above code line if object is more than one. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jobj = jarray.getJSONObject(0)

    99. parsing of string into json in android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for(int i=0
      2. i<jarray.length()
      3. i++){ JSONObject jobj = jarray.getJSONObject(i)
      4. }

    100. parsing of string into json in android

      If my answer is helping you then please accept it. first your json String if it's contain result then it is not valid you can check it here to make valid json string just use String.replace as now JSON String is valid you can parse it as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonarray = new JSONArray(finaljson)
      2. for (int i = 0
      3. i < jarray.length()
      4. i++) { JSONObject jsonobj = jarray.getJSONObject(i)
      5. // get value from json object here String str_City=jsonobj.getString("City")
      6. ///....}

    101. parsing of string into json in android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jarray = new JSONArray(result)
      2. JSONObject jobj = jarray.getJSONObject(0)

    102. parsing of string into json in android

      first your json String if it's contain result then it is not valid you can check it here to make valid json string just use String.replace as now JSON String is valid you can parse it as . The Json array contains only one entry the index is 0 To handle it right access the json array using a for loop . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jarray = new JSONArray(result)
      2. for (int i = 0
      3. i < jarray.length()
      4. i++) { JSONObject jobj = jarray.getJSONObject(i)
      5. .....}

    103. I would like to see an example web method that passes an array of objects from aspx webservice

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(strJSONResponse)

    104. I would like to see an example web method that passes an array of objects from aspx webservice

      You will have to use JSON to get array of objects in Android so Now let me start to give step by step demo for parsing the same JSON resoponse Step 1 create a JSONObject with the received response string Step 2 Get the main object from the created json object by using getJSONObject method Step 3 Now this FirstObject contains 2 strings namely attr1,attr2 and a object namely sub.So get 2 strings by using getString method. and get a sub object by using the same getJSONObject method as we have used above Step 4 Now this sub sub-object contains 1 array namely sub1. details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONObject subObject = object.getJSONObject("sub")

      Positive Reactions
      1. wow!
      2. Thanks a lot.
      3. superb.
      Other Reactions
      1. Let me try this and get back to you..

    105. I would like to see an example web method that passes an array of objects from aspx webservice

      Thanks in advance. You will have to use JSON to get array of objects in Android so Now let me start to give step by step demo for parsing the same JSON resoponse Step 1 create a JSONObject with the received response string Step 2 Get the main object from the created json object by using getJSONObject method Step 3 Now this FirstObject contains 2 strings namely attr1,attr2 and a object namely sub.So get 2 strings by using getString method. details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONObject object = jsonObject.getJSONObject("FirstObject")

      Positive Reactions
      1. wow!
      2. Thanks a lot.
      3. superb.
      Other Reactions
      1. Let me try this and get back to you..

    106. How to dynamically add to a nested element in a JSON object in Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( theJsonString )

    107. I am new to JSON , is there any way to validate a json- key value pair

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsob = new JSONObject(StringRepresentationOfJson)

    108. Json parsing in array java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for(int i = 0
      2. i < jsonArray.length()
      3. i++){ JSONObject obj = jsonArray.getJSONObject(i)
      4. ...}

    109. Passing JSONObject/JSONArray from AsyncTask to UI Thread

      In onPostExecute you can access the UI Thread. If you take a look at AsyncTask documentation you will see that you can actually pass pretty much everything to onPostExecute and onProgressUpdate The example below can be changed to any other parameters where the generic types are ordered like that 1. details

      Reactions - Positive 0, Negative 0, Others 0

      1. private class JsonAsyncTask extends AsyncTask<URL, String, JSONObject> { protected JSONObject doInBackground(URL... urls) { // usrls to connect to server publishProgress(/* some string you got, for example */ // ... return /* a json object you created from data received */
      2. } protected void onProgressUpdate(String ... progress) { // parse the string and display it } protected void onPostExecute(JSONObject result) { // display results from the JSONObject } }

    110. Can't Convert to JSONArray for showing in ListView

      i search for it and found that is for utf-8 encode. use instead of Because your json String is collection of JsonOject's it's not contains any JsonArray. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject notes = jSon.getJSONObject("notes")

      Positive Reactions
      1. copy JSON in the lisnk and show correctly the result.
      2. Thanks.
      Other Reactions
      1. after this i changed to JSONObject c notes.getJSONObject(Integer.toString(i));.
      2. fix it.
      3. i use this link to create the code : [^] ( URL_http://www.androidhive.info/2012/05 /how-to-connect-android-with-php-mysql/).
      4. not to JSONArray change it to JSONObject and see your json string it only contain "{" means it contain only json object's not any jsonarray.
      5. I changed to JSONArray but not fixed.

    111. Convert Json Array to Java Array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = "{\"result\":\"success\",\"source\":\"chat\",\"tag\":null,\"success\":{\"message\":\"%message%\",\"time\":%time%,\"player\":\"%player%\"}}"
      2. JSONObject obj = new JSONObject(json)
      3. JSONObject success = obj.getJSONObject("success")
      4. System.out.println("<" + success.get("player") + "> " + success.get("message"))

    112. JSON.getString doesn't return null

      The other option would be to use the method and then based on the returned boolean value proceed with your option. Something like But then I don't think there's much of a difference between the your current implementation and this. details

      Reactions - Positive 2, Negative 0, Others 0

      1. public String getMessageFromServer(JSONObject response) { return ((response.has("message") && !response.isNull("message"))) ? response.getString("message") : null
      2. }

      Positive Reactions
      1. +1 for pointing out the correct method to check for a null value.
      2. The isNUll-call is cleaner and should be preferred towards relying on Object and casting.
      Other Reactions
      1. But I don't agree when you say there is not much difference.

    113. How to automatically convert long values to strings in Spring?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main( String[] args ) throws IllegalAccessException, InvocationTargetException{ Object m = new Object()
      2. m.setA("aa")
      3. m.setB((long) 22222)
      4. Object2 m2 = new Object2()
      5. BeanUtils.copyProperties(m2, m)
      6. //now you can convert m2 to JSONobject}

    114. Android how to sort JSONArray of JSONObjects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class JSONComparator implements Comparator<JSONObject> {
      2. public int compare(
      3. JSONObject a,
      4. JSONOBject
      5. b) { //valA and valB could be any simple type, such as number, string, whatever String valA = a.get("keyOfValueToSortBy")
      6. String valB = b.get("keyOfValueToSortBy")
      7. if (valA > valB) return 1
      8. if (valA < valB) return -1
      9. return 0
      10. }
      11. }

    115. How can I iterate JSONObject to get individual items

      How about this. This sample code using "org.json.JSONObject" . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING)
      2. JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo")
      3. String ip_address = ipinfo.getString ("ip_address")
      4. JSONObject location = ipinfo.getJSONObject ("Location")
      5. String latitude = location.getString ("latitude")
      6. System.out.println (latitude)

    116. How do I clone an org.json.JSONObject in Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static java.lang.String[] getNames(JSONObject jo)

    117. How do I clone an org.json.JSONObject in Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public JSONObject(JSONObject jo, java.lang.String[] names)

    118. I have json in that there is one other json object so how to check second Json object is null

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < jsonArray.length()
      3. i++) { JSONObject jsonObject = jsonArray.getJSONObject(i)
      4. String outerstr = jsonObject.getString("category")
      5. JSONObject json = new JSONObject(outerstr)
      6. String id = json.getString("cat_id")
      7. String title = json.getString("cat_title")
      8. Log.i("title ", title)
      9. Log.i("desc ", id)
      10. yourList.add( new yourClassObject(id,title))
      11. } } catch (Exception e) { e.printStackTrace()
      12. }

    119. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject()

    120. String to json conversion issue

      that is enough to do all the required things. Simple Example** First Prepare a String Now to parse the String Object U just have to pass the String to the constructor method That should do it and voila. details

      Reactions - Positive 3, Negative 6, Others 0

      1. JSONObject jObj = new JSONObject(jStr)

      Positive Reactions
      1. I just corrected it.
      2. I hope this helps.
      3. Thanks anyway for pointing that out.
      Negative Reactions
      1. Oh my bad!
      2. I just confused org.codehaus.jettison.json.JSONObject with net.sf.json.JSONObject .
      3. I'm realllly sorry!
      4. @David Grant is correct and I'm wrong.
      5. URL_http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html .
      6. Guys sorry for the wrong information.
      Other Reactions
      1. I take it back.
      2. -1: net.sf.json.JSONObject doesn't have a String constructor.

    121. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jettison.json.JSONObject
      2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
      3. }public static void main(String[] args) throws Exception { System.out.println("here")
      4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
      5. JSONObject jsonObj = new JSONObject(json)
      6. run(jsonObj)
      7. }

    122. Get Vector object from JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject#put(String, Object)

    123. Json String can't decode using json-simple toolkit java

      I had this problem and I have fixed it. Here is my code snippet I got the yahoo user guid from the request body. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object obj = JSONValue.parse(response.getBody())
      2. JSONObject jsonObject = (JSONObject) obj
      3. Object gu_obj = jsonObject.get("guid")

    124. Create json object in servlet

      You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object. Console you will get output JSON data "key1":"value1","key2":"value2","key3":"value3" . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonData = new JSONObject()
      2. jsonData.put("key1", "value1")
      3. jsonData.put("key2", "value2")
      4. jsonData.put("key3", "value3")
      5. System.out.println("JSON data: "+jsonData.toString())

    125. How to execute Mustache template with JSON/String on Android?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. mustacheTemplate.execute(JSONUtils.toMap(new JSONObject(myString)))

    126. JSONObject cannot be cast to JSONArray, SimpleJSON

      If that is the case how can I iterate through off things contained in arr and get each item. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. for(int i = 0
      2. i < arr.size()
      3. i++) { JsonObject p = (JsonObject)arr.get(i)
      4. System.out.println(p.get("time").getAsString())
      5. }

      Positive Reactions
      1. Thanks, I had just found out that was the answer a few seconds before you updated :D.
      Other Reactions
      1. see update answer.
      2. The method getString(String) is undefined for the type JSONObject.

    127. How to get JSON object from HTTP request in Java

      If you are using URLConnection you should be able to read the stream instead of getting a response object see . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Scanner scanner = new Scanner(wikiRequest.openStream())
      2. String response = scanner.useDelimiter("\\Z").next()
      3. JSONObject json = Util.parseJson(response)
      4. scanner.close()

    128. Parsing JSON string in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject geoObject = jObject.getJSONObject("geodata")

    129. JSONObject in JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.getJSONArray(String)

    130. JSONObject in JSONObject

      JSONObject provides accessors for a number of different data types including nested JSONObjects and JSONArrays using ml#getJSONObject%28java.lang.String%29 CODESNIPPET_JAVA5 on.org/javadoc/org/json/JSONObject.html#getJSONArray%28java.lang.String%29 CODESNIPPET_JAVA6 . Given your JSON you'd need to do something like this Note the lack of error handling here for instance the code assumes the existence of the nested members you should check for null and there's no Exception handling. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject json = getJSONfromURL(URL)
      2. JSONObject user = json.getJSONObject("user")
      3. JSONObject status = user.getJSONObject("status")
      4. int stat1 = status.getInt("stat1")

      Positive Reactions
      1. thanks.
      Other Reactions
      1. @CheJami I did, fixed.
      2. Did you mean JSONObject user json.getJSONObject("user")?

    131. JSONObject in JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.getJSONObject(String)

    132. How to truncate float to %.2f format while encoding it to JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject js_price = JSONObject(String.format("{\"price\": %.2f}", f)

    133. How to truncate float to %.2f format while encoding it to JSON?

      Try using String.format Edit Is using a float required or could you try double. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. double d = 52.92
      2. JSONObject js_price = new JSONObject()
      3. js_price.put("price", d)
      4. Log.d("json", js_price.toString())

      Other Reactions
      1. double doesn't solve the problem - there will be another value which will result in loooong part after point.
      2. And how I will put this in JSON-string in number-format?
      3. yep, this (String.format(...)) will not work at all as js_price is not a float...
      4. I should have read your question more carefully.
      5. I would suggest using BigDecimal instead of float for currency.

    134. java - 400 when posting JSONObject to Restful Web Service

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes("application/json")@Produces("text/plain")@Path("/add/{device}")public String addApp(@PathParam("device") String device, JSONObject json) {

    135. Java XStream with HashMap

      The most efficient process I have come up with so far was to create a toJson function inside my classes to work just like toString. Example Converts the objects data output string into Json format public JsonObject toJson So for you implement a similar process while populating your map. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject temp = new JsonObject()
      2. temp.addProperty(tagName,floatData)
      3. return temp
      4. }

    136. How to Create following String Dynamically

      Even if you fix this issue there is a chance that it will fail for another condition. A sample algorithm with recursion would be . details

      Reactions - Positive 0, Negative 1, Others 0

      1. public String generateQuery(JSONObject json_obj) {if(single_json_obj) return generated_query_for_single_condition
      2. //else complex json with inner childrenelse return generateQuery(innerJSONObject)}

      Negative Reactions
      1. @Afrin He has already used recursion, but it wasn't enough to get the expected result.
      Other Reactions
      1. can you explain more.

    137. How should I escape strings in JSON?

      It can be used to escape JavaScript codes. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.simple.JSONObject
      2. String test = JSONObject.escape("your string")

    138. creating json string using JSONObject and JSONArray

      your getId returns an int then it will be added as a bare JSON int. I'll assume that calls toString on the value but I can't verify this. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject.put(String, Object)

      Positive Reactions
      1. Thanks !!
      Other Reactions
      1. ?
      2. @JAVAGeek: javascript arrays have a length property, see edit.
      3. how can i traverse each object in a loop....arr[0] .. arr[1] would be ok but if i don't know number of items then how can i access them ??
      4. i think this is exactly what i was looking for..

    139. Java parse JSON for android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. new JSONObject(feed)

    140. Java parse JSON for android

      You are making your life much harder. then extract the keyvalue pairs . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void extractJsonData(String feed){ feed = feed.trim()
      2. JSONObject json = new JSONObject(feed)

    141. Java parse JSON for android

      then extract the keyvalue pairs . That's because your JSONObject is empty You have to pass respose string to JSONObject's constructor like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(response)

    142. Java parse JSON for android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject =new JSONObject()

    143. How can I catch a JSON object sent from an android app to a servlet with doGet method?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ HttpSession httpSession = request.getSession(false)
      2. JSONObject jJobObject = JSONObject.fromObject(request.getParameter("data"))
      3. JJob jJob = (JJob) JSONObject.toBean(jJobObject, JJob.class)
      4. String strTerm = (String) httpSession.getAttribute("terminal")
      5. Integer term = null
      6. try { term = Integer.parseInt(strTerm)
      7. } catch(Exception e) { // } jJob = PersoJobService.createJob(jJob, (Integer) httpSession.getAttribute("userId"), term )
      8. writeResponse(JSONObject.fromObject(jJob), request, response)
      9. }

    144. get json from HttpResponse

      SagarHatekar Will do cant accept it in a while though. If I'm returning a JSON string from my web service I usually want to get it back to a JSON object like so . details

      Reactions - Positive 1, Negative 0, Others 0

      1. String response = client.getResponse()
      2. if (responseCode == 200) { JSONObject obj = new JSONObject(response)
      3. }

      Positive Reactions
      1. Looks cleaner, thanks for the input.
      Other Reactions
      1. However, the issue was php related, see my comment above.

    145. How to parse a JSONArray of JSONObjects in JAVA?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public YourObject(JSONObject json) { if (!json.isNull("referral_fullname")) this.referral_fullname = json.optString("referral_fullname", null)
      2. if (!json.isNull("referral_balance")) this.referral_balance = json.optString("referral_balance", null)
      3. }

    146. How to parse a JSONArray of JSONObjects in JAVA?

      0 is way bad please work on it by accepting answers . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = <your json>
      2. JSONObject jObject = new JSONObject(s)
      3. Map<String,String> map = new HashMap<String,String>()
      4. Iterator iter = jObject.keys()
      5. while(iter.hasNext()){ String key = (String)iter.next()
      6. String value = jObject .getString(key)
      7. map.put(key,value)
      8. }

    147. How to parse a JSONArray of JSONObjects in JAVA?

      You structure is now an object with two fields 0 and 1 which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jso
      2. for(int i = finalResult.lenght-1
      3. i >=0
      4. i--){ jso = finalResult.get(i)
      5. // jso == {"referral_fullname":"Name 1","referral_balance":"500"} [whatever]}

    148. JSON parsing not working with JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String result = "{\"name\":\"test\", \"num1\":1.0, \"num2\":2.0}"
      2. JSONObject data = new JSONObject(result)
      3. System.out.println(data.getString("name"))
      4. System.out.println(data.get("num1"))
      5. System.out.println(data.get("num2"))

    149. create Json Object from String Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < finalResult.length()
      3. i++) { JSONObject message = finalResult.getJSONObject(i)
      4. String content= message.getString("content")
      5. ... ...}

    150. How to make JSONObject ignore special meaning for 'null' and print it as literal null

      json-smart Both of these libraries work as required by your implementation with a String null value. I tested both with sample code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj = new JSONObject()
      2. obj.put("test", "null")
      3. // Both libraries print out {"test":"null"}System.out.println(obj.toJSONString())

    151. String from server cannot be converted to JSONObject?

      How are you doing it. It should work with . details

      Reactions - Positive 9, Negative 5, Others 0

      1. JSONObject object = new JSONObject (yourString)

      Positive Reactions
      1. It would be interesting to log the responseBody string before converting to JSONObject to see what you are getting there.
      2. Your code looks correct to me.
      3. I have tried to parse your response and it's working.
      4. I tried to create a JSONObject with your response and it works: JSONObject object new JSONObject ("{\"VALS\":{\"VAL1\":\"hello\",\"VAL2\":\"hello2\",\"VAL3\":\"hello3\"}}");.
      5. I fixed it see my answer below :) Your explanation came pretty close, so I accepted it.
      6. It looks like a special character escaping issue... it just can't be anything else...
      7. Thank you all for responding, I gave you all +1s.
      8. TO EVERYBODY: miguel.rodelas's theory is most likely correct.
      9. Thank you for your reply.
      Negative Reactions
      1. I think the problem is in the String.
      2. I tried everyone's suggestion, but the error always occurs at _new JSONObject()_. I'm going to experiment more and update this thread about my progress.
      3. The problem was within the string itself, not the Java.
      4. The server probably used some incorrect encoding, but I'm really not sure.
      5. it must be something my server is doing... this time I created a JSONObject from within my code, passed it on to my server via POST, then I had the server pass the EXACT same JSONObject right back to my code, but I still get the error.
      Other Reactions
      1. :(.
      2. Can you edit your question including the code where you get the response?
      3. ok I edited the question to include the code.
      4. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/12065/discussion-between-miguel - rodelas-and-user1408996).
      5. I don't know how you are passing the string, but maybe you have to scape the quotes \".
      6. Yes that is exactly how I am doing it:JSONObject response=new JSONObject(responseBody);.
      7. Maybe some quotes.
      8. Can you try to log in Eclipse the String you are getting as response and copy it here?

    152. Android, Parsing JSON object

      inc machine new time and timeSecond. A JSON array data structure would have looked like this signifies an array. details

      Reactions - Positive 4, Negative 1, Others 0

      1. JSONObject idObject = ...getJSONObject("id")
      2. String machine = idObject.get("machine")

      Positive Reactions
      1. Thanks Chin i could parse it.
      2. This part, i would strongly recommend that you look into a good JSON library, GSON from Google seems to be a good one.
      3. Welcome Hesam :).
      4. Wow, the tool is amazing thank you for sharing with us :).
      Negative Reactions
      1. Thanks dear Chin, based on what you mentioned i found that "id" is wrong key because i don't need its items.
      Other Reactions
      1. Based of what, should i have to parse "response" string?
      2. Here is a short tutorial: URL_http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/ .
      3. How to get body, publishedDate, refKey and title?
      4. To get publishedDate, refKey, and title, you would only need JSONObject jObject new JSONObject(response); String publishedDate jObject.get("publishedDate"); and so on.

    153. Android Json and null values

      This is the reason JSONObject.NULL exists to represent a null JSON value. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. json.getString("hello").equals(JSONObject.NULL)
      2. // should be falsejson.getString("bye").equals(JSONObject.NULL)
      3. // should be true

      Positive Reactions
      1. Thanks for your answer but imho and since an JSONException is thrown if the key don't exists is more logical returning null when the item is null.
      Other Reactions
      1. You'll need to take up stylistic preferences with the developers of the library itself :p.

    154. Java: Parsing more than one Json Object in a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObj = new JSONObject(jsonStr)

    155. How should I escape strings in JSON?

      StringEscapeUtils.escapeJavaScript StringEscapeUtils.escapeEcmaScript should do the trick too. I have not spent the time to make 100 certain but it worked for my inputs enough to be accepted by online JSON validators although it does not look any better than I simply use velocity tools in my project already my manual JSON building was within a velocity template . details

      Reactions - Positive 0, Negative 0, Others 0

      1. org.codehaus.jettison.json.JSONObject.quote("your string")

    156. HttpPost response doesn't return the json object

      That means something wrong with the request. should't this be like and in case if server return JSONString and then get values . details

      Reactions - Positive 1, Negative 1, Others 0

      1. say JSONObject data = new JSONObject(resp)

      Positive Reactions
      1. @Sandy..no sandy..it still gives me a null value.
      Negative Reactions
      1. @AmilaFonseka.. sorry see my edits..
      Other Reactions
      1. erm..no sandy..we can't pass an entity object to 'toString' method..

    157. JSON Java check element is a JSONArray or JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. if (element instanceof JSONObject) { Map<String, Object> map = json2Java.getMap(element .toString())
      2. if (logger.isDebugEnabled()) { logger.debug("Key=" + key + " JSONObject, Values=" + element)
      3. } for (Entry<String, Object> entry : map.entrySet()) { if (logger.isDebugEnabled()) { logger.debug(entry.getKey() + "/" + entry.getValue())
      4. } jsonMap.put(entry.getKey(), entry.getValue())
      5. } }

    158. How to convert a String into a JSONArray?

      If you are going to use the JSONArray/JSONObject classes then you need to instead create a JSONObject object for each of your players and add those to the JSONArray. For example the following code would create a JSONObject add the name of your player to the object and then add it to the JSONArray However a much simpler way of doing JSON serialization is to use GSON gson/ . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject playerJsonObject = new JSONObject()
      2. playerJsonObject.put("name", player.getName())
      3. jsonArray.put(playerJsonObject)

    159. Parsing JSON and save them on SQLite Database

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObject = new JSONObject(String json)

    160. Is it possible to post a JSON in JQuery to a server that GET the JSON in Jersey JAVA

      As ManseUK implied in the comment you're sending a POST request and expecting a GET handler to receive it. Either change the GET in the handler to POST or do something really silly like delegate POST to GET . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @POST@Consumes("application/json")@Produces("application/json")public String getResourceByPost(JSONObject obj) throws IOException { return getResource(obj)
      2. }

      Other Reactions
      1. Really, just change your @GET annotation to a @POST.
      2. There is no recursion, the @POST annotated method is called getResourceByPost.
      3. This will be a eternal recursion when getResource() calls getResource()?And I'm wondering does the variable obj even contains the json data the has been posted?

    161. Parsing an JSON file from webpage and storing the values in 2d array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject aussieCurrency=finalJson.getJSONObject("AUD")

    162. caching JSON from webservice on android - pattern?

      Here's a simply way to do this that doesn't involve a service threads alarms etc. just define a wrapper around your JSON like the implementation of does the following in other words lazy-fetch the fresh json from the network when you need it. details

      Reactions - Positive 0, Negative 0, Others 0

      1. class MyJson { JSONObject getJson() { ... }
      2. }

    163. Json Array not properly generated

      Thanks Guillaume Polet. Place inside the loop . details

      Reactions - Positive 1, Negative 0, Others 0

      1. while (products.readRecord()){ JSONObject jo = new JSONObject()
      2. String productID = products.get("user")
      3. int j = Integer.parseInt(productID)
      4. // etc

      Positive Reactions
      1. Thanks jabal...

    164. Json Array not properly generated

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jo = new JSONObject()

    165. Json Array not properly generated

      You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your inside the loop and it should work fine. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject jo = new JSONObject()

      Positive Reactions
      1. Thanks Guillaume Polet.

    166. How to find specified name and its value in JSON-string from Java?

      But you should create a result class for getting an instance from JSON string. If you can't clarify the result class use json-simple Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. details

      Reactions - Positive 0, Negative 0, Others 0

      1. // import static org.hamcrest.CoreMatchers.is
      2. // import static org.junit.Assert.assertThat
      3. // import org.json.simple.JSONObject
      4. // import org.json.simple.JSONValue
      5. // import org.junit.Test
      6. @Testpublic void json2Object() { // given String jsonString = "{\"name\" : \"John\",\"age\" : \"20\"," + "\"address\" : \"some address\"," + "\"someobject\" : {\"field\" : \"value\"}}"
      7. // when JSONObject object = (JSONObject) JSONValue.parse(jsonString)
      8. // then @SuppressWarnings("unchecked") Set<String> keySet = object.keySet()
      9. for (String key : keySet) { Object value = object.get(key)
      10. System.out.printf("%s=%s (%s)\n", key, value, value.getClass() .getSimpleName())
      11. } assertThat(object.get("age").toString(), is("20"))
      12. }

    167. Android Twitter String to Json Array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // Instantiate a JSON object from the request responseJSONObject obj = new JSONObject(json)

    168. convert foursquare http response to JSON for java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonObjLoc = new JSONObject(myLocation)

    169. Android - Parsing Twitter JSON for image url

      The profile_image_url property is not a property in that top level array element but rather a child element of the user property. To access the profile_background_image_url you would have to do something roughly like the following . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject userObject = jsonObject.getJSONObject ("user")
      2. String url = userObject.getString("profile_image_url")

    170. How to nest objects when building JSON with JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject object = JSONObject.getJSONObject("{\"jsonrpc\": \"2.0\", \"method\": \"Files.GetSources\", \"params\":{\"media\":\"music\"}, \"id\": 1}")

    171. How to nest objects when building JSON with JSONObject

      You can create another object that holds media":"music and then put that in the original JSONObject or you can just pass this whole string into the JSONObject constructor and have it parse it for you. Chaining put like this is possible because put returns the object it was called on for this exact purpose. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONOjbect obj = new JSONObject().put("jsonrpc", "2.0") .put("method", "Files.GetSources").put("id", 1) .put("params", new JSONObject.put("media", "music"))

    172. How to nest objects when building JSON with JSONObject

      You're going to have to be a lot more specific if you expect any useful replies. If you're asking how you'd put the nested params object in there you'd probably do To use an array per your comments below) you'd do something like this . details

      Reactions - Positive 3, Negative 2, Others 0

      1. JSONObject params = new JSONObject()
      2. params.put("media", "music")
      3. obj.put("params", params)

      Positive Reactions
      1. thanks!
      2. Yes, you can nest things as far as you like (using the same principle from this answer).
      3. That worked!
      Negative Reactions
      1. Sorry for being vague, could you multiple nested?
      2. For example .. for one like this..{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["resume", "genre", "studio", "tagline", "runtime", "fanart", "thumbnail", "file", "plot", "plotoutline", "year", "lastplayed", "rating"]}, "id": 1}.
      Other Reactions
      1. For your properties, you'd use a [JSONArray]( URL_http://developer.android.com/reference/org/json/JSONArray.html ) instead of JSONObject.
      2. you've helped me out a lot.
      3. I've updated my answer with an example.

    173. Parsing JSON File Java

      You can use a library like JSON-java . yes you can use jacson to parse it but there is more easy way to do it its Jsonme lib import org.json.me you dont have to add jar file to use it yes its more easy but if your project is complex i advice you to use jacson lib . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj = new JSONObject("{'var1':'val1','var2':200})
      2. String var1=obj.getString("var1")
      3. int var2=obj.getInt("var2")

    174. Parsing JSON File Java

      as Bozho said create class structure that reflacts JSON and then use jacson library as follow refer dXaUha1%2a7mzQ5rbUNdXa5X%2a5P%2a2jIE%2a83NPAyaHmtNq8Osjece5RtO5C/jsonparsingwi thjackson.pdf Parsing-JSON-File-Java . You can use a library like JSON-java . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.JSONObject
      2. String jsonString = ...JSONObject object = new JSONObject(jsonString)
      3. String status = object.getString("status")

    175. Most effecient conversion of ResultSet to JSON?

      In addition to suggestions made by Jim Cook. One other thought is to use a switch instead of if-elses . details

      Reactions - Positive 1, Negative 0, Others 0

      1. while(rs.next()) { int numColumns = rsmd.getColumnCount()
      2. JSONObject obj = new JSONObject()
      3. for( int i=1
      4. i<numColumns+1
      5. i++) { String column_name = rsmd.getColumnName(i)
      6. switch( rsmd.getColumnType( i ) ) { case java.sql.Types.ARRAY: obj.put(column_name, rs.getArray(column_name))
      7. break
      8. case java.sql.Types.BIGINT: obj.put(column_name, rs.getInt(column_name))
      9. break
      10. case java.sql.Types.BOOLEAN: obj.put(column_name, rs.getBoolean(column_name))
      11. break
      12. case java.sql.Types.BLOB: obj.put(column_name, rs.getBlob(column_name))
      13. break
      14. case java.sql.Types.DOUBLE: obj.put(column_name, rs.getDouble(column_name))
      15. break
      16. case java.sql.Types.FLOAT: obj.put(column_name, rs.getFloat(column_name))
      17. break
      18. case java.sql.Types.INTEGER: obj.put(column_name, rs.getInt(column_name))
      19. break
      20. case java.sql.Types.NVARCHAR: obj.put(column_name, rs.getNString(column_name))
      21. break
      22. case java.sql.Types.VARCHAR: obj.put(column_name, rs.getString(column_name))
      23. break
      24. case java.sql.Types.TINYINT: obj.put(column_name, rs.getInt(column_name))
      25. break
      26. case java.sql.Types.SMALLINT: obj.put(column_name, rs.getInt(column_name))
      27. break
      28. case java.sql.Types.DATE: obj.put(column_name, rs.getDate(column_name))
      29. break
      30. case java.sql.Types.TIMESTAMP: obj.put(column_name, rs.getTimestamp(column_name))
      31. break
      32. default: obj.put(column_name, rs.getObject(column_name))
      33. break
      34. } } json.put(obj)
      35. }

      Positive Reactions
      1. Looping backwards (comparing the index zero) is also faster (than comparing the index to an expression).

    176. JSONObject when element doesn't exist

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. if (command.isNull("def") { // Handle 'def' not being there} else { JSONObject def = command.getJSONObject("def")
      2. }

    177. How should I escape strings in JSON?

      See 2.5 of the RFC. Try this . details

      Reactions - Positive 2, Negative 0, Others 0

      1. org.codehaus.jettison.json.JSONObject.quote("your string")

      Positive Reactions
      1. Definitely the best solution!
      2. but this does not quoting of braces like [{.
      Other Reactions
      1. Thx.

    178. Json to Map

      Use the following code Utilize the libraries com.google.gson.Gson com.google.common.reflect.TypeToken and java.lang.reclect.Type . This way its works like a Map . details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONObject fieldsJson = new JSONObject(json)
      2. String value = fieldsJson.getString(key)

      Negative Reactions
      1. Yes, but you must wrap every single get in try/catch because of JSON exceptions.
      Other Reactions
      1. you could write a class, JsonMap implements Map

    179. Java JSONException while creating JSONArray

      is trying to use a JSONObject to initialize a JSONArray. You need to use since your content is a JSON object. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = new JSONObject(content)

      Positive Reactions
      1. Thanks a lot sir, this helped me a lot!.

    180. Extract json informations

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jobj = new JSONObject(theStringFromFacebook)
      2. String uid = jobj.getString("id")

    181. Java json parse

      Don't mention it D. You should try JavaJson from source forge you can parse that this way and so on. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject json = JsonObject.parse("...")
      2. /* * or also JsonObject.parse(inputStream)
      3. */then you can get fields this way:String title = json.getString("title")
      4. String username = json.get("user", "username").toString()

    182. Object isn't a valid JSONArray

      pics key has jsonObject as value not a jsonArray. you have to iterate through all the keys and get each information of picture. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject picsJson = data.getJSONObject("pics")

    183. JSON Proxy in Java / Play! Framework

      here comes an example for doing async http calls e.g. to facebook api . details

      Reactions - Positive 0, Negative 0, Others 0

      1. WSRequest req = WS.url("https://graph.facebook.com/100001789213579")
      2. Promise<HttpResponse> respAsync = req.getAsync()
      3. HttpResponse resp = await(respAsync)
      4. JsonElement jsonResp = resp.getJson()
      5. JsonObject jsonObj = new JsonObject()
      6. jsonObj.add("facebook-response", jsonResp)
      7. renderJSON(jsonObj)

    184. Trying to return data from PHP with JSON to Android.....

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. //Example of the content of result:// {"name":"john"} This would be the result returned from the restfull request// This the above JSON would be stored in a variable of type String.JSONObject obj = new JSONObject(result)
      2. //JSONObject's constructor accepts a string as parameter

    185. Returning value from an IF statement

      Vinoth Cheers ). Declare the 2 string outside the if statement like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String newcontent_mod,newtype_mod
      2. if ((object.has("message"))) { JSONObject message = object.getJSONObject("message")
      3. newtype_mod = object.getJSONObject("message") .getString("type")
      4. newcontent_mod = object.getJSONObject("message") .getString("content")
      5. objSample = new GetSetMethod()
      6. objSample.setnewcontent_mod(newcontent_mod)
      7. objSample.setnewtype_mod(newtype_mod)
      8. Log.v("##"+newcontent_mod,"V "+newtype_mod)
      9. }

      Other Reactions
      1. This won't compile -- after the if clause, the local variable newcontent_mod/newtype_mod may not have been initialized.

    186. Returning value from an IF statement

      . You can declare it outside the if statement and just assign the value to these variables for example otherwise You can declare both at Global level i.e. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String newtype_mod=""
      2. String newcontent_mod=""
      3. if ((object.has("message"))) { JSONObject message = object.getJSONObject("message")
      4. newtype_mod = object.getJSONObject("message") .getString("type")
      5. newcontent_mod = object.getJSONObject("message") .getString("content")
      6. objSample = new GetSetMethod()
      7. objSample.setnewcontent_mod(newcontent_mod)
      8. objSample.setnewtype_mod(newtype_mod)
      9. Log.v("##"+newcontent_mod,"V "+newtype_mod)
      10. }

      Positive Reactions
      1. @Vinoth Cheers :).
      Other Reactions
      1. "You can declare it outside the if statement and just assign the value to these variables" This line sorted my problem thanks.

    187. how to convert XML to JSON in java?

      You can grab a set of Java classes to handle JSON at There you can find the XML and JSONObject classes among others. This code could work for you . details

      Reactions - Positive 5, Negative 0, Others 0

      1. public String XMLtoJSON(String xml) { JSONObject jsonObj = XML.toJSONObject(xml)
      2. String json = jsonObj.toString()
      3. return json
      4. }

      Positive Reactions
      1. Excellent observation, @RajeevM, :-).
      2. Hi antur123, I can't able to handle XML.toJSONObject(xml) because i can able to resolve XML, how can i resolve this?
      3. Thanks, just edited it!.
      4. Ooops!
      5. please help me.
      Other Reactions
      1. In @antur123's answer, I believe all instances of "string" should be "String", in which case that code should work.
      2. I believe you just must use XML.java class at URL_http://json.org/java/ .
      3. @selladurai Any reason this is not selected as the answer?

    188. Passing JSON object

      It looks like it would work except you have to build your own jar apparently. You can see the constructor right in the source-for-JSONObject.java . details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject(String)

      Positive Reactions
      1. Actually I searched the internet and found another jar that is having the number of constructors found in the documentation of JSONLink is this: URL_http://code.google.com/p/wave-robot-java - client/downloads/detail?name=json.jar&can=4&q=So in order to use JSON correctly we have to include two jars namely the one we get from JSON website and one getting from Google website(Link given) While using we have to specifically tell the compiler whose constructor we want to call.
      Negative Reactions
      1. Oops, my bad.
      Other Reactions
      1. @RyanStewart: [Yes it does.
      2. ]( URL_http://www.json.org/javadoc/org/json/JSONObject.h tml#JSONObject(java.lang.String)).
      3. URL_http://www.json.org/javadoc/org/json/JSONObject.htmllook at this.
      4. I never noticed it hiding among those others.
      5. If you look at the docs, that JSONObject doesn't have a JSONObject(String) constructor, either.

    189. Java representation of JSON Object

      Here are some nice Tutorials for JSON that will help you out. GSON JSON android-listview JSON-Example-with-source-code UPDATED Try like this . details

      Reactions - Positive 3, Negative 1, Others 0

      1. try { JSONObject object = new JSONObject(jsonString)
      2. JSONObject myObject = object.getJSONObject("recentlyMarkedTerritories")
      3. for (int i = 0
      4. i < object.length()
      5. i++) { JSONObject myObject2 = myObject.getJSONObject(Integer.toString(i))
      6. System.out.println(myObject2.toString(2))
      7. } } catch (Exception e) { e.printStackTrace()
      8. }

      Positive Reactions
      1. I accepted your answer because I found it much easier to handle the native Android JSONObject than the Google GSONObject and am now using that.
      2. I have been looking all over these and I cant find anything that explains how to name or iterate through objects with numeric names like in the json above..
      3. Thanks for the great links and shove in the right direction!.
      Negative Reactions
      1. Sorry, I sort of hid the "...." after the second entry.
      Other Reactions
      1. Is this your complete JSON String...?
      2. The list may go to 5 or maybe 100.
      3. No it is not the complete string..
      4. Almost seems not achievable in java?
      5. Do I literally have to declare every class for "0", "1", "2", "3"....?

    190. Parsing JSON from YouTube API

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < items.length()
      3. i++) { JSONObject videoObject = items.getJSONObject(i)
      4. String title = videoObject.getString("title")
      5. String videoId = videoObject.getString("id")
      6. }

    191. Getting JSONObject from JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class DeletedTrsWrapper {
      2. public String company_id
      3. public String username
      4. public String date
      5. public int report_id
      6. public DeletedTrsWrapper(JSONObject obj) {
      7. company_id = obj.getString("companyid")
      8. username = obj.getString("username")
      9. date = obj.getString("date")
      10. report_id = obj.getInt("reportid")
      11. }
      12. }

    192. Getting JSONObject from JSONArray

      The get companyid username date . start from you can iterate through JSONArray and use values directly or create Objects of your own type which will handle data fields inside of each deletedtrs_array member Iterating Own object type . details

      Reactions - Positive 0, Negative 0, Others 0

      1. for(int i = 0
      2. i < deletedtrs_array.length()
      3. i++){ JSONObject obj = deletedtrs_array.getJSONObject(i)
      4. Log.d("Item no."+i, obj.toString())
      5. // create object of type DeletedTrsWrapper like this DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj)
      6. // String company_id = obj.getString("companyid")
      7. // String username = obj.getString("username")
      8. // String date = obj.getString("date")
      9. // int report_id = obj.getInt("reportid")
      10. }

    193. Java, Parse JSON Objects that I know are null

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.optString(String key)

    194. How do I extract value from Json

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = (JSONObject) JSONSerializer.toJSON(data)
      2. double coolness = json.getDouble( "coolness" )
      3. int altitude = json.getInt( "altitude" )
      4. JSONObject pilot = json.getJSONObject("pilot")
      5. String firstName = pilot.getString("firstName")
      6. String lastName = pilot.getString("lastName")
      7. System.out.println( "Coolness: " + coolness )
      8. System.out.println( "Altitude: " + altitude )
      9. System.out.println( "Pilot: " + lastName )

    195. How to parse a dynamic JSON key in a Nested JSON result

      Use JSONObject-keys() to get the key and then iterate each key to get to the dynamic value. Roughly the code will look like . details

      Reactions - Positive 9, Negative 0, Others 0

      1. // searchResult refers to the current element in the array "search_result" JSONObject questionMark = searchResult.getJSONObject("question_mark")
      2. Iterator keys = questionMark.keys()
      3. while(keys.hasNext()) { // loop to get the dynamic key String currentDynamicKey = (String)keys.next()
      4. // get the value of the dynamic key JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey)
      5. // do something here with the value... }

      Positive Reactions
      1. Momo it was a Nice answer.
      2. High time SO supported multiple upvotes for a great answer!.
      3. Glad to be able to help :) Let me know if you have any question.
      4. :P Thanks again for the prompt response!
      5. You saved me an all-nighter!.
      6. Thanks, momo!
      7. +1 Awesome!
      8. Had it not been for your sample code, I'd ended up asking another question!
      9. That worked just fine!
      Other Reactions
      1. We (the SO Community) are all here to help out.
      2. I saw your earlier response which suggested using keys() and I ended up printing the outer keys.
      3. :).

    196. JSON Java check element is a JSONArray or JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject category=jsonObject.optJSONObject("Category")

    197. Android how to get int type in JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. //method 1String myJson = " {errorCode:"+errorCode+"}"
      2. ErrorCode = new JSONObject(myJson)
      3. //method 2ErrorCode = new JSONObject()
      4. ErrorCode.put("errorCode", errorCode)
      5. // jsonObject.put(String key,Object value)

    198. Android how to get int type in JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.getInt("key")

    199. How to convert HTTP Request Body into JSON Object in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public void doPost(HttpServletRequest req, HttpServletResponse res) { JSONObject jsonObj = requestParamsToJSON(req)
      2. // Now "jsonObj" is populated with the request parameters. // e.g. {"key1":"value1", "key2":["value2a", "value2b"], ...}}

    200. How to convert HTTP Request Body into JSON Object in Java

      Thanks . Assuming you're using an vlet/http/HttpServlet.html HttpServlet and a JSON library like json-simple you could do something like this With example usage . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public JSONObject requestParamsToJSON(ServletRequest req) { JSONObject jsonObj = new JSONObject()
      2. Map<String,String[]> params = req.getParameterMap()
      3. for (Map.Entry<String,String[]> entry : params.entrySet()) { String v[] = entry.getValue()
      4. Object o = (v.length == 1) ? v[0] : v
      5. jsonObj.put(entry.getKey(), o)
      6. } return jsonObj
      7. }

      Positive Reactions
      1. turns out you can do: JSONObject json new JSONObject(slingHttpServletRequest.getParameterMap()); as well - your method does give a bit more control over what is allowed into the json object (such as introducing a white/black list) - which is nice.

    201. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

      Minor nitpick what you have is a Java list not JSON array but you want to send it as a JSON array. you basically use certain classes in java like the ones defined here convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set here is code for the same for more . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj=new JSONObject()
      2. obj.put("name","foo")
      3. obj.put("num",new Integer(100))
      4. obj.put("balance",new Double(1000.21))
      5. obj.put("is_vip",new Boolean(true))
      6. obj.put("nickname",null)
      7. StringWriter out = new StringWriter()
      8. obj.writeJSONString(out)
      9. String jsonText = out.toString()
      10. System.out.print(jsonText)

    202. JSON - Iterate through JSONArray

      Then to access the string elements in the objects JSONObject get them out by element name. If you need the names of the elements in the JSONObject you can use the static utility method to do so. details

      Reactions - Positive 4, Negative 1, Others 0

      1. JSONObject.getNames(JSONObject)

      Positive Reactions
      1. I want iterate though each of them and get thier component name and value.
      2. I want to iterate though the objects in the array and get thier component and thier value.
      3. Thanks again.
      4. Programmer Bruce: I dont want to get the name for a specific element, I want to check if the array has 4 element, then get thier name and thier value or if the array has 5 elements then get thier name and value.
      Negative Reactions
      1. Iam sorry man, sometimes I even confuess myself.
      Other Reactions
      1. Updated answer per latest requirements.
      2. In my example the first object has 3 components, the scond has 5 and the third has 4 components.
      3. You keep changing the requirements.
      4. To check the number of elements in a JSON object, you can use JSONObject.getNames(objects).length.
      5. To check the number of object components in the array, use getArray.length().
      6. Are you checking if the array has 4 object components, or if an object in the array has 4 elements?
      7. All of the pieces of the code necessary to do what you want are already posted on this page.
      8. This code should do what I want to do.

    203. JSON - Iterate through JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject objects = getArray.getJSONObject(i)

    204. JSON - Iterate through JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject objects = getArray.optJSONObject(i)

    205. JSON - Iterate through JSONArray

      If you need the names of the elements in the JSONObject you can use the static utility method to do so. Get the value for the first element and the value for the last element. details

      Reactions - Positive 4, Negative 1, Others 0

      1. String[] elementNames = JSONObject.getNames(objects)

      Positive Reactions
      1. I want iterate though each of them and get thier component name and value.
      2. I want to iterate though the objects in the array and get thier component and thier value.
      3. Thanks again.
      4. Programmer Bruce: I dont want to get the name for a specific element, I want to check if the array has 4 element, then get thier name and thier value or if the array has 5 elements then get thier name and value.
      Negative Reactions
      1. Iam sorry man, sometimes I even confuess myself.
      Other Reactions
      1. Updated answer per latest requirements.
      2. In my example the first object has 3 components, the scond has 5 and the third has 4 components.
      3. You keep changing the requirements.
      4. To check the number of elements in a JSON object, you can use JSONObject.getNames(objects).length.
      5. To check the number of object components in the array, use getArray.length().
      6. Are you checking if the array has 4 object components, or if an object in the array has 4 elements?
      7. All of the pieces of the code necessary to do what you want are already posted on this page.
      8. This code should do what I want to do.

    206. JSON - Iterate through JSONArray

      Are you using the org.json API or some other Java-to/from-JSON library. Change to or to depending on which JSON-to/from-Java library you're using. details

      Reactions - Positive 4, Negative 1, Others 0

      1. JSONObject objects = getArray.getJSONArray(i)

      Positive Reactions
      1. I want iterate though each of them and get thier component name and value.
      2. I want to iterate though the objects in the array and get thier component and thier value.
      3. Thanks again.
      4. Programmer Bruce: I dont want to get the name for a specific element, I want to check if the array has 4 element, then get thier name and thier value or if the array has 5 elements then get thier name and value.
      Negative Reactions
      1. Iam sorry man, sometimes I even confuess myself.
      Other Reactions
      1. Updated answer per latest requirements.
      2. In my example the first object has 3 components, the scond has 5 and the third has 4 components.
      3. You keep changing the requirements.
      4. To check the number of elements in a JSON object, you can use JSONObject.getNames(objects).length.
      5. To check the number of object components in the array, use getArray.length().
      6. Are you checking if the array has 4 object components, or if an object in the array has 4 elements?
      7. All of the pieces of the code necessary to do what you want are already posted on this page.
      8. This code should do what I want to do.

    207. JSON - Iterate through JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.names()

    208. How to parse a JSON Input stream

      link Indicates that for Android JSONTokener only takes a String. . details

      Reactions - Positive 2, Negative 3, Others 0

      1. import org.json.JSONObject
      2. JSONObject json = new JSONObject(urlInputStream.toString())

      Positive Reactions
      1. Since JSONObject isn't part of the standard library, you should really specify which one you're using.
      2. coz when someone will copy code from question and add code from your answer will get "InputStream@XXXXXx is not valid json" (or smthng like this) then i could change vote ...
      Negative Reactions
      1. Sorry but this answer is just plain wrong.
      2. Did not deserve a downvote.
      3. You can exclude it and this is still the answer.
      Other Reactions
      1. If your response is valid JSON then it will work every time.
      2. It's not for copying and pasting since everyone's application is different.
      3. This is out of the scope of the answer.
      4. im sure that not a content of stream...
      5. I really cant understand why this answer is accepted.
      6. @Selvin my answer is only an example.
      7. could you add this stream reading example from my link to your answer?
      8. So why even oracle dont use it in samples?
      9. I tried in.toString() but it returns: getClass().getName() + '@' + Integer.toHexString(hashCode()) .. See my answer below.
      10. org.json package has always been available to me in Android sdk.
      11. This is entirely optional but since the JsonObject constructor requires a String, this ensures that we give it a String.
      12. and what urlInputStream.toString() returns?
      13. I agree with Martin, the stream needs to be read in.
      14. Ooops, I didn't notice the android tag.
      15. @Selvin toString() only ensures that your content is a string.
      16. @Selvin yes in fact, it returns the string of the server response.
      17. URL_http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html can you show me where in InputStream documentation is written that toString method return content of stream?

    209. JSON ClassCastException

      It looks as though you are getting a String object instead of the JSONObject that you require. Assuming that all objects in studentsGradeArray are supposed to be JSON Objects More information can be found in the lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html JSONObject documentation . details

      Reactions - Positive 4, Negative 2, Others 0

      1. for( Object myObject : studentsGradeArray ) { JSONObject studentGradeJSON = JSONObject.fromObject(myObject)
      2. // the rest of your code}

      Positive Reactions
      1. My answer has been updated to use the proper API; let me know if that works.
      2. I'll correct my answer.
      3. Because you have added the cast from String as well.
      4. Thanks NT3RP.. which ones more reliable.
      Negative Reactions
      1. Thanks NT3RP, Exception is gone :).
      2. Sorry, I was assuming you were using [this library]( URL_http://www.json.org/javadoc/org/json/JSONObject.html) .
      Other Reactions
      1. Your solution or amadeus's?
      2. Actually I do have this library imported in my class "import net.sf.json.JSONObject;".
      3. Didnt work: The constructor JSONObject(String) is undefined.

    210. JSONObject to String Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject a = new JSONObject("{hello1: hi, hello2: hey}")
      2. String b = a.toString().substring(1, a.toString().lenght() -1)

    211. JSONObject to String Android

      Just do a substring or string replace. Pseudo substring Example Pseudo string replace Example . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject a = new JSONObject("{hello1: hi, hello2: hey}")
      2. String b = a.toString().replace("{", "")
      3. String c = b.toString().replace("}", "")

    212. JSON order mixed up

      However if we need to have an ordered JSON one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject. Normally the order is not preserved as below. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Testdef void testOrdered() { Map obj = new LinkedHashMap() obj.put("a", "foo1") obj.put("b", new Integer(100)) obj.put("c", new Double(1000.21)) obj.put("d", new Boolean(true)) obj.put("e", "foo2") obj.put("f", "foo3") obj.put("g", "foo4") obj.put("h", "foo5") obj.put("x", null) JSONObject json = (JSONObject) obj logger.info("Ordered Json : %s", json.toString()) String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}""" assertEquals(expectedJsonString, json.toString()) JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)}

    213. json Deserializer in to target object

      Write a custom method on the Affiliate object something like Affiliate#mergeWith(Affiliate other). . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject jsonResponse = new JSONObject(responseString)

      Positive Reactions
      1. Thanks, but where is the merge here?
      Other Reactions
      1. I want to merge the object with an existing object.
      2. see my code again mayby, Thanks.
      3. URL_http://stackoverflow.com/questions/2403132/concat-multiple-jsonobjects .

    214. READ JSON String in servlet

      You aren't actually parsing the json. . details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONObject jObj = new JSONObject(request.getParameter("mydata"))
      2. // this parses the jsonIterator it = jObj.keys()
      3. //gets all the keyswhile(it.hasNext()){ String key = it.next()
      4. // get key Object o = jObj.get(key)
      5. // get value session.putValue(key, o)
      6. // store in session}

      Negative Reactions
      1. Thanks....I now know the mistake I was doing.

    215. Better way to determine if value exists in JSON feed

      The best solution I've come up with though not implemented yet is to simply have a try-catch around the do you know of any better solution that is more graceful when the class scales to several optional properties in the JSON feed). You might use the JSONObject function has . details

      Reactions - Positive 5, Negative 0, Others 0

      1. if(myJSONObject.has("UnpublishDate")) { //it has it, do appropriate processing}

      Positive Reactions
      1. Helped me !
      2. Ah, great!
      3. after a lot searched getting awesome one thing has hahahahahaha lol!!!
      4. Missed that one - thanks!.
      5. Thanks.
      Other Reactions
      1. !.

    216. JSONObject text must begin with '{'

      Try trimming EDIT I thought this was javascript. Try trimming it using Java code instead If that still doesn't work then show what the first character from the string is You should be expecting 123 the curly braces. details

      Reactions - Positive 8, Negative 3, Others 0

      1. JSONObject allCDs = new JSONObject(objectString.trim())

      Positive Reactions
      1. Cutting off the "null" works :)) But perhaps I shall somehow correct, how I create the String !
      2. @wong - Pleasure to help.
      3. BufferedReader inReader new BufferedReader(new InputStreamReader(is)); String line inReader.readLine(); while (line != null){ objectString+= line; //System.out.println(line); line inReader.readLine(); }.
      4. The original is totally correct and checked.
      5. Thanks.
      6. Welcome!
      7. This objectString.trim() fixed it for me ;)!.
      8. When you please, you can upvote the answer and accept it (click on the tick next to the answer).
      Negative Reactions
      1. Thank You very much anyway for finding the real mistake of my Code, Thank You :).
      2. you are right, but actually this comma-mistake was just because I shortened the JSONObject for this Question at stackoverflow.
      3. That means I my String objectString is not correct.
      Other Reactions
      1. I see that you are new to StackOverflow.
      2. got it.
      3. The JSONObject(objectString.replace(/^\s+/,"")); does not work :(( .replace is only for chars.
      4. answer updated with another possibility.
      5. What is the type and content of the variable objectString?
      6. the type is a String, which contains information from this JSONObject:.
      7. @wong Updated answer based on objectString string.
      8. Answer edited again.
      9. The first character from the string is "null" and then comes the curly brace.
      10. The .trim did not work.
      11. This was my Code to create it:.
      12. URL_http://home.de.napster.com/search-cgi/getListByIDXML?CLIENTTYPE=client&type_id artistalbum&result_type=album&select_by=artist&select_value=10451807&format=j son&count=10&index=0&LFM=N&COUNTRYCODE=DE&EXPLICIT=Y.

    217. JSONObject text must begin with '{'

      You may be passing the STRING to JSONObject with leading spaces. Try trimming EDIT I thought this was javascript. details

      Reactions - Positive 8, Negative 3, Others 0

      1. JSONObject allCDs = new JSONObject(objectString.replace(/^\s+/,""))

      Positive Reactions
      1. Cutting off the "null" works :)) But perhaps I shall somehow correct, how I create the String !
      2. @wong - Pleasure to help.
      3. BufferedReader inReader new BufferedReader(new InputStreamReader(is)); String line inReader.readLine(); while (line != null){ objectString+= line; //System.out.println(line); line inReader.readLine(); }.
      4. The original is totally correct and checked.
      5. Thanks.
      6. Welcome!
      7. This objectString.trim() fixed it for me ;)!.
      8. When you please, you can upvote the answer and accept it (click on the tick next to the answer).
      Negative Reactions
      1. Thank You very much anyway for finding the real mistake of my Code, Thank You :).
      2. you are right, but actually this comma-mistake was just because I shortened the JSONObject for this Question at stackoverflow.
      3. That means I my String objectString is not correct.
      Other Reactions
      1. I see that you are new to StackOverflow.
      2. got it.
      3. The JSONObject(objectString.replace(/^\s+/,"")); does not work :(( .replace is only for chars.
      4. answer updated with another possibility.
      5. What is the type and content of the variable objectString?
      6. the type is a String, which contains information from this JSONObject:.
      7. @wong Updated answer based on objectString string.
      8. Answer edited again.
      9. The first character from the string is "null" and then comes the curly brace.
      10. The .trim did not work.
      11. This was my Code to create it:.
      12. URL_http://home.de.napster.com/search-cgi/getListByIDXML?CLIENTTYPE=client&type_id artistalbum&result_type=album&select_by=artist&select_value=10451807&format=j son&count=10&index=0&LFM=N&COUNTRYCODE=DE&EXPLICIT=Y.

    218. JSONObject text must begin with '{'

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject allCDs = new JSONObject(objectString.substring(objectString.indexOf('{')))

    219. How to read stringified JSON string in Java

      using can be realy easy. See lib.sourceforge.net/snippets.html and . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{'dealerName':'NPD STATION SDN BHD', 'dealerID': 1, 'dealerReputation': 2.0, 'dealerActive': true}"
      2. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str )

    220. Parse JSON object with string and value only

      ex Thank . You need to get a list of all the keys loop over them and add them to your map as shown in the example below . details

      Reactions - Positive 1, Negative 0, Others 0

      1. String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}"
      2. JSONObject jObject = new JSONObject(s)
      3. JSONObject menu = jObject.getJSONObject("menu")
      4. Map<String,String> map = new HashMap<String,String>()
      5. Iterator iter = menu.keys()
      6. while(iter.hasNext()){ String key = (String)iter.next()
      7. String value = menu.getString(key)
      8. map.put(key,value)
      9. }

      Positive Reactions
      1. simple but very efficient, thank you.

    221. Porting from one Json to javas org.json.JSONObject, missing keys not acting the same

      Assuming you are using the code from this library I believe you want Check out the documentation for the JSONObject class Also all classes from the library are documented here . To see if the JSONObject has a key use the function. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.has(String key)

    222. simplest way to read json from a URL in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject(java.lang.String source) Construct a JSONObject from a source JSON text string.

    223. How do I provide the following json output using java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.JSONObject
      2. ......JSONObject json = new JSONObject()
      3. json.put("city", "Mumbai")
      4. json.put("country", "India")
      5. ...String output = json.toString()

    224. Java HashMap vs JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.put()

    225. Java HashMap vs JSONObject

      Because of this performance will be almost identical. adds a null check and will throw an exception if a key isn't found. details

      Reactions - Positive 2, Negative 1, Others 0

      1. JSONObject.get()

      Positive Reactions
      1. True.
      2. I guess overall it is more of a question of POJOs vs library-specific abstractions; I like to keep data format aspects closer to edges.
      Negative Reactions
      1. Actually I disagree with this -- since JSONObject is specific to one library, unlike Maps, exposing it as a type will add more coupling to specific library and its datatypes.
      Other Reactions
      1. @Stax, I can see your point.
      2. But, if you need to de-couple a part of the code, you can always extract the data into a map yourself.
      3. So I would not categorically say it should always be used.

    226. Getting JSONObject from String

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject(java.lang.String

    227. Getting JSONObject from String

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject o = (JSONObject) JSONSerializer.toJSON(request.getParameter("WHATEVER"))

    228. Getting JSONObject from String

      when in doubt assume it's the reference JSON library from json.org. Very simple Edit Since you use json-lib it's for you. details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONObject o = new JSONObject(request.getParameter("WHATEVER"))

      Negative Reactions
      1. JSONObject does not have any constructor with String argumentwhich API you are using ?
      Other Reactions
      1. ?
      2. I'm using the JSON library from json.org.

    229. Parse string to JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject.keys()

    230. Nested JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject flash = json.getJSONObject(0)
      2. JSONObject Flash = flash.getJSONObject("Flash")
      3. int starttime = Flash.getInt("Starttime")

    231. Convert JSON to HashMap using Gson in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject obj = JSONObject.fromObject(strRepresentation)
      2. Iterator i = obj.entrySet().iterator()
      3. while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next()
      4. System.out.println("Key: " + e.getKey())
      5. System.out.println("Value: " + e.getValue())
      6. }

    232. Parsing a JSON Response from a .Net webservice

      The plug in parsed the response automatically(By using Visual Studio's Add Web Refrence") so I never had to deal with this until I jumped platforms and now I'm lost. Looks like you're using the org.json package.I suggest you use the net.sf.json package at lib.sourceforge.net/ It contains a lot more functionality and you can create a JSONObject or JSONArray from a string or other objects like Map with no effort with similar for JSONArrays). details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONObject.fromObject(obj)

      Positive Reactions
      1. Thanks!
      Negative Reactions
      1. I'll give this a shot and see what happens.

    233. Library to encode/decode from json to java.util.Map?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject(map)

    234. Library to encode/decode from json to java.util.Map?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of * the JSONObject. */ public JSONObject(Map map)

    235. Library to encode/decode from json to java.util.Map?

      You can view the site from Json.org for the list of good JSON libraries in Java. JSon.org's own implementation JSONObject can do just that.From their JavaDoC you can do To convert JSON String back to object and you can access values like Constructor JavaDoC Construct a JSONObject from a source JSON text string. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jsonString = "{\"name\" : \"some name\", \"age\" : 10}"
      2. JSONObject json = new JSONObject(jsonString)

      Other Reactions
      1. This goes from Map -> JSONObject, but the questioner wants both directions.

    236. Java - JSON Null Exception

      input sample stacktrace Thanks. For me this works with json-lib-2.3-jdk15 Actually the null value becomes an instance of JSONNull. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String json = "{\"prop1\":\"val1\", \"prop2\":123, \"prop3\":null}"
      2. JSONObject jsonObject = JSONObject.fromObject(json)
      3. HashMap<String, Object> map = (HashMap<String, Object>) JSONObject.toBean(jsonObject, HashMap.class)

      Positive Reactions
      1. Thanks for your answer.

    237. concat multiple JSONObjects

      Any ideas besides pulling them all apart and individually adding in by puts. If you want a new object with two keys Object1 and Object2 you can do If you want to merge them so e.g. details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONObject Obj1 = (JSONObject) jso1.get("Object1")
      2. JSONObject Obj2 = (JSONObject) jso2.get("Object2")
      3. JSONObject combined = new JSONObject()
      4. combined.put("Object1", Obj1)
      5. combined.put("Object2", Obj2)

      Negative Reactions
      1. I am trying to use your second code snippet in Android, but I don't see a static getNames function on JSONObject.
      Other Reactions
      1. It was only mentioned here URL_http://www.json.org/javadoc/org/json/JSONObject.html .
      2. @AustynMahoney, not sure about the history, but for Android you can use the instance method [JSONObject.names]( URL_http://developer.android.com/reference/or g/json/JSONObject.html#names%28%29).
      3. It was not mentioned in android documentation also.
      4. @AustynMahoney It was not there in android json library i tried it already.
      5. Was this added in a newer version of the org.json library?

    238. concat multiple JSONObjects

      If you want a new object with two keys Object1 and Object2 you can do If you want to merge them so e.g. a top level object has 5 keys Stringkey1 ArrayKey StringKey2 StringKey3 StringKey4) I think you have to do that manually This would be a lot easier if JSONObject implemented Map and supported putAll. details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1))
      2. for(String key : JSONObject.getNames(Obj2)){ merged.put(key, Obj2.get(key))
      3. }

      Negative Reactions
      1. I am trying to use your second code snippet in Android, but I don't see a static getNames function on JSONObject.
      Other Reactions
      1. It was only mentioned here URL_http://www.json.org/javadoc/org/json/JSONObject.html .
      2. @AustynMahoney, not sure about the history, but for Android you can use the instance method [JSONObject.names]( URL_http://developer.android.com/reference/or g/json/JSONObject.html#names%28%29).
      3. It was not mentioned in android documentation also.
      4. @AustynMahoney It was not there in android json library i tried it already.
      5. Was this added in a newer version of the org.json library?

    239. concat multiple JSONObjects

      It was only mentioned here . You can create a new JSONObject like this With this code if you have any repeated keys between Obj1 and Obj2 the value in Obj2 will remain. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject merged = JSONObject()
      2. JSONObject[] objs = new JSONObject[] { Obj1, Obj2 }
      3. for (JSONObject obj : objs) { Iterator it = obj.keys()
      4. while (it.hasNext()) { String key = (String)it.next()
      5. merged.put(key, obj.get(key))
      6. }}

      Positive Reactions
      1. I didn't know about the static method JSONObject.getNames, it makes the code much simpler, see Matthew's answer below which reduces the code using it.

    240. Generate Java class from JSON?

      For me this script was helpful. It process only flat JSON and don't take care of types but automate some routine . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{" + "'title': 'Computing and Information systems'," + "'id' : 1," + "'children' : 'true'," + "'groups' : [{" + "'title' : 'Level one CIS'," + "'id' : 2," + "'children' : 'true'," + "'groups' : [{" + "'title' : 'Intro To Computing and Internet'," + "'id' : 3," + "'children': 'false'," + "'groups':[]" + "}]" + "}]" + "}"
      2. JSONObject json = new JSONObject(str)
      3. Iterator<String> iterator = json.keys()
      4. System.out.println("Fields:")
      5. while (iterator.hasNext() ){ System.out.println(String.format("public String %s
      6. ", iterator.next()))
      7. } System.out.println("public void Parse (String str){")
      8. System.out.println("JSONObject json = new JSONObject(str)
      9. ")
      10. iterator = json.keys()
      11. while (iterator.hasNext() ){ String key = iterator.next()
      12. System.out.println(String.format("this.%s = json.getString(\"%s\")
      13. ",key,key ))
      14. System.out.println("}")

    241. Accessing members of items in a JSONArray with Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for (int i = 0
      2. i < recs.length()
      3. ++i) { JSONObject rec = recs.getJSONObject(i)
      4. int id = rec.getInt("id")
      5. String loc = rec.getString("loc")
      6. // ...}

    242. Using JSON to return a Java Map

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject(Map)

    243. List<Map<String,Object>> to org.json.JSONObject?

      It would be more consistent with JSON to make a Map of Maps instead of a List of Maps. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject(list)
      2. Iterator<?> it = json.keys()
      3. while (keyed.hasNext()) { String x = (String) it.next()
      4. JSONObject jo2 = new JSONObject(jo.optString(x))
      5. }

  4. Strugging to simplify HashMap object placement

    Also this will cause an error if so maybe you want to add some logic in there to say if it is 6 then add it to a different group. . .. details

    1. List<List<HashMap<String, String>>> childData = new ArrayList<List<HashMap<String, String>>>()
    2. for(int i=0
    3. i<6
    4. i++) childData.add(new ArrayList<HashMap<String,String>>())
    5. for (int i = 0
    6. i < jArray.length()
    7. i++) { JSONObject jObj = jArray.getJSONObject(i)
    8. HashMap<String, String> hm = new HashMap<String, String>()
    9. hm.put("moduleName", jObj.getString("moduleName"))
    10. hm.put("startTime", (jObj.getString("startTime")).substring(0, 5))
    11. hm.put("endTime", (jObj.getString("endTime")).substring(0, 5))
    12. hm.put("group", jObj.getString("group"))
    13. hm.put("roomName", jObj.getString("roomName"))
    14. hm.put("firstName", jObj.getString("firstName"))
    15. hm.put("lastName", jObj.getString("lastName"))
    16. childData.get(Integer.parseInt(jObj.getString("day"))).add(hm)
    17. }

    Other Reactions
    1. +1.
    2. Also, as a brevity thing _plus_ "proper" use of polymorphism, you should probably change the HashMap generic param to just Map: childData new ArrayList>>() (and in other places where you have a List>).

    • See Also (3)
    1. How to get data as an json array from a server and convert it in to java array to use in android application

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. int size = the_json_array.length()
      2. ArrayList<JSONObject> arrays = new ArrayList<JSONObject>()
      3. for (int i = 0
      4. i < size
      5. i++) { JSONObject another_json_object = the_json_array.getJSONObject(i)
      6. //Blah blah blah... arrays.add(another_json_object)
      7. }//FinallyJSONObject[] jsons = new JSONObject[arrays.size()]
      8. arrays.toArray(jsons)
      9. //The end...

    2. Android how to sort JSONArray of JSONObjects

      This isn't exact code but something like Of course if you have nested objects this can get a little trickier. If the value(s you want to sort on live in the top level it may not be soo bad Then use a comparator like this to sort Again this makes some assumptions about the homogeneity of the data in your JSONArray. details

      Reactions - Positive 0, Negative 0, Others 0

      1. List<JSONObject> jsonValues = new ArrayList<JSONOBject>()
      2. for (int i = 0
      3. i < myJsonArray.length()
      4. i++) jsonValues.add(myJsonArray.getJSONObject(i))

      Other Reactions
      1. You can't compare Strings that way due to the fact that Java doesn't have operator overloading.
      2. update line Collections.sort(jsonValues);.
      3. The example should return valA.compareTo(valB).
      4. This example is close, but it doesn't compile.

    3. How to parse a JSON and turn its values into an Array?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. int size = the_json_array.length()
      2. ArrayList<JSONObject> arrays = new ArrayList<JSONObject>()
      3. for (int i = 0
      4. i < size
      5. i++) { JSONObject another_json_object = the_json_array.getJSONObject(i)
      6. //Blah blah blah... arrays.add(another_json_object)
      7. }//FinallyJSONObject[] jsons = new JSONObject[arrays.size()]
      8. arrays.toArray(jsons)
      9. //The end...

  5. Using MyApplication class in android for JSON data

    You commented the intent.puExtraCode Also look at the source code of ArrayAdapter 2.2 rev1 Line 355 is Indicating that the textview in your adapter is null. in which case you should look at So i suggest the following changes MyApplication class DisplayActivity Snaps . .. details

    1. public class MainActivity extends Activity { // Declare Variables JSONObject jsonobject
    2. JSONArray jsonarray
    3. ListView listview
    4. Adapter adapter
    5. ProgressDialog mProgressDialog
    6. ArrayList<HashMap<String, String>> arraylist
    7. ArrayList<String> arraylist2
    8. static String NAME = "rank"
    9. Button btn
    10. StringBuilder result
    11. MyApplication mapp
    12. //get MyApplication reference @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
    13. // Get the view from listview_main.xml setContentView(R.layout.activity_main)
    14. arraylist = new ArrayList<HashMap<String, String>>()
    15. arraylist2 = new ArrayList<String>()
    16. mapp=MyApplication.getInstance()
    17. listview = (ListView) findViewById(R.id.listView)
    18. btn = (Button) findViewById(R.id.button1)
    19. btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // Toast.makeText(MainActivity.this,"///"+arraylist.size(), 1000).show()
    20. result = new StringBuilder()
    21. for (int i = 0
    22. i < arraylist.size()
    23. i++) { if (adapter.mysparse.get(i) == true) { result.append(arraylist.get(i).get(MainActivity.NAME))
    24. arraylist2.add(arraylist.get(i).get(MainActivity.NAME))
    25. result.append("\n")
    26. } } mapp.setArrayListMapData(arraylist2)
    27. Toast.makeText(MainActivity.this,result, 1000).show()
    28. Intent n = new Intent(MainActivity.this, DisplayActivity.class)
    29. // n.putExtra("buffer", arraylist2)
    30. startActivity(n)
    31. } })
    32. // Execute DownloadJSON AsyncTask new DownloadJSON().execute()
    33. } // DownloadJSON AsyncTask private class DownloadJSON extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute()
    34. // Create a progressdialog mProgressDialog = new ProgressDialog(MainActivity.this)
    35. // Set progressdialog title // mProgressDialog.setTitle("Fetching the information")
    36. // Set progressdialog message mProgressDialog.setMessage("Loading...")
    37. mProgressDialog.setIndeterminate(false)
    38. // Show progressdialog mProgressDialog.show()
    39. } @Override protected Void doInBackground(Void... params) { // Create an array try { // Retrieve JSON Objects from the given URL address String s = getData()
    40. jsonobject = new JSONObject(s)
    41. // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("restaurants")
    42. for (int i = 0
    43. i < jsonarray.length()
    44. i++) { HashMap<String, String> map = new HashMap<String, String>()
    45. jsonobject = jsonarray.getJSONObject(i)
    46. // Retrive JSON Objects map.put(MainActivity.NAME, jsonobject.getString("Person_Name"))
    47. Log.d("jsonobject", jsonobject.toString())
    48. // Set the JSON Objects into the array arraylist.add(map)
    49. } } catch (JSONException e) { Log.e("Error", e.getMessage())
    50. e.printStackTrace()
    51. } return null
    52. } @Override protected void onPostExecute(Void args) { // Pass the results into ListViewAdapter.java adapter = new Adapter(MainActivity.this, arraylist)
    53. // Set the adapter to the ListView listview.setAdapter(adapter)
    54. // Close the progressdialog mProgressDialog.dismiss()
    55. } } private String getData() { String _response = null
    56. try { HttpClient httpclient = new DefaultHttpClient()
    57. httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
    58. HttpGet request = new HttpGet("http://54.218.73.244:7004/DescriptionSortedPrice/")
    59. HttpResponse response = httpclient.execute(request)
    60. HttpEntity resEntity = response.getEntity()
    61. _response =EntityUtils.toString(resEntity)
    62. } catch(Exception e) { e.printStackTrace()
    63. } return _response
    64. } public class Adapter extends BaseAdapter implements OnCheckedChangeListener { // Declare Variables Context context
    65. LayoutInflater inflater
    66. ArrayList<HashMap<String, String>> data
    67. HashMap<String, String> resultp = new HashMap<String, String>()
    68. SparseBooleanArray mysparse
    69. public Adapter(Context context, ArrayList<HashMap<String, String>> arraylist) { this.context = context
    70. data = arraylist
    71. mysparse = new SparseBooleanArray(data.size())
    72. } @Override public int getCount() { return data.size()
    73. } @Override public Object getItem(int position) { return position
    74. } @Override public long getItemId(int position) { return position
    75. } public View getView(final int position, View convertView, ViewGroup parent) { // Declare Variables TextView name
    76. CheckBox chk
    77. inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE)
    78. View itemView = inflater.inflate(R.layout.single_item, parent, false)
    79. // Get the position resultp = data.get(position)
    80. // Locate the TextViews in listview_item.xml name = (TextView) itemView.findViewById(R.id.textView1)
    81. chk = (CheckBox) itemView.findViewById(R.id.checkBox1)
    82. // Capture position and set results to the TextViews name.setText(resultp.get(MainActivity.NAME))
    83. chk.setTag(position)
    84. chk.setChecked(mysparse.get(position, false))
    85. chk.setOnCheckedChangeListener(this)
    86. return itemView
    87. } public boolean isChecked(int position) { return mysparse.get(position, false)
    88. } public void setChecked(int position, boolean isChecked) { mysparse.put(position, isChecked)
    89. } public void toggle(int position) { setChecked(position, !isChecked(position))
    90. } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub mysparse.put((Integer) buttonView.getTag(), isChecked)
    91. } } }

    Positive Reactions
    1. Its simple add it at the beginning of onClick.
    2. As i said earlier intents is a good choice for your case.
    3. In onClick of MainActivity.java .... where i need to add this line !
    4. @smriti3 clear the list in onClick.
    5. just clear the list in onClick.
    6. Finally with such crystal clear explanation it works .. one more question .... this i found out how to do it ... say i select carl, bangalore .... i see the results carl, bangalore in listview ...... suppose i go back deselect carl now i click to next screen ...... i see carl , bangalore, bangalore ..... i know it is just incrementing values one above the other ..... if i want final results to be only bangalore if i deselect carl .. how can i achieve this in android ... i am refering to dynamic main memory manupilation.
    7. Yes now got it .... im beginner to Java to so ..... thanks for your guidance.
    Negative Reactions
    1. .... i tried few places .... i can see memory refreshing but results are not appearing proper ... My USE CASE :: I select 2 items ..press button i should see 2 items in result .... then if i press back button and deselect one item .... press button again .... i should see only the selected item in result which is 1.
    2. To your question answer lies here.
    3. The term mainmemory is also not right.
    Other Reactions
    1. But you want application class.
    2. @smriti3 i would use intent instead of application class.
    3. remove all data populate with new data.
    4. @smriti3 that is bcoz of Application class.
    5. arraylist2.clear();.
    6. Yes, Exactly .... A way to reset the things once the results are displayed .... im just refering logic ... i dont know if its possible ?
    7. This is java stuff nothing to do with android.
    8. arraylist2.clear().
    9. secondly where are all you tried those?
    10. Also i would use a Viewholder pattern.
    11. @Raghunandan.... Ok .... is there a possible way so that when i go to ResultActivity ... where the results are displayed ... i just could refesh the mainmemory ...that could be a quick fix and is it possible in android .?
    12. Anyway the rest is upto you to decide.
    13. I really don't understand.
    14. .... if you want i can make a new question for this if it is out of context of present question.
    15. @smriti3 what do you mean by refresh mainmemory?
    16. URL_http://developer.android.com/reference/android/app/Application.html .
    17. @smriti3 your use case has nothing to do with this.

  6. Validate JSON String

    None .. details

    1. public boolean isJSONValid(String test){ boolean valid = false
    2. try { new JSONObject(test)
    3. valid = true
    4. } catch(JSONException ex) { valid = false
    5. } return valid
    6. }

    • See Also (28)
    1. Convenient way to extract data from the MtGox/PubNub JSON API?

      The important bits are between the marks BEGIN OF IMPORTANT PART and END OF IMPORTANT PART. For clarity I've removed the imports which you can add back in with the appropriate hotkeys in most IDEs it's Ctrl+Shift+O in Eclipse). details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class PubNubMtGoxBeanExample {
      2. private static final String MTGOXPUBNUB_SUBSCRIBE_KEY =
      3. "sub-c-50d56e1e-2fd9-11e3-a041-02ee2ddab7fe"
      4. private static final String MTGOXPUBNUB_BTCEUR_CHANNEL = "0bb6da8b-f6c6-4ecf-8f0d-a544ad948c15"
      5. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
      6. static {
      7. OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      8. }
      9. public static void main(String[] args) throws PubnubException {
      10. Pubnub pubnub = new Pubnub("demo", MTGOXPUBNUB_SUBSCRIBE_KEY)
      11. pubnub.subscribe(
      12. MTGOXPUBNUB_BTCEUR_CHANNEL,
      13. new Callback() {
      14. @Override
      15. public void successCallback(
      16. String channel,
      17. Object
      18. message) { // BEGIN OF IMPORTANT PART JSONObject messageJson = (JSONObject) message
      19. JSONObject tickerJson
      20. try {
      21. tickerJson = messageJson.getJSONObject("ticker")
      22. } catch (JSONException e) {
      23. throw new RuntimeException(e)
      24. }
      25. MtGoxTicker ticker
      26. try { // the following line is the most important, because it maps from the JSONObject to the MtGoxTicker class ticker = OBJECT_MAPPER.readValue(tickerJson.toString(), MtGoxTicker.class)
      27. } catch (JsonParseException e) {
      28. throw new RuntimeException(e)
      29. } catch (JsonMappingException e) {
      30. throw new RuntimeException(e)
      31. } catch (IOException e) {
      32. throw new RuntimeException(e)
      33. }
      34. String currency = ticker.getLast().getCurrency()
      35. BigDecimal value = ticker.getLast().getValue()
      36. System.out.println(currency + " " + value)
      37. // END OF IMPORTANT PART } @Override public void connectCallback(String channel, Object message) { System.out.println("connectCallback on channel:" + channel + " : " + message.getClass() + " : " + message.toString())
      38. }
      39. @Override
      40. public void disconnectCallback(String channel, Object message) {
      41. System.out.println(
      42. "disconnectCallback on channel:"
      43. + channel
      44. + " : "
      45. + message.getClass()
      46. + " : "
      47. + message.toString())
      48. }
      49. @Override
      50. public void reconnectCallback(String channel, Object message) {
      51. System.out.println(
      52. "reconnectCallback on channel:"
      53. + channel
      54. + " : "
      55. + message.getClass()
      56. + " : "
      57. + message.toString())
      58. }
      59. @Override
      60. public void errorCallback(String channel, PubnubError error) {
      61. System.out.println("errorCallback on channel " + channel + " : " + error.toString())
      62. }
      63. })
      64. }
      65. }

      Other Reactions
      1. can you mark this question as "Answered" or let us know if we can provide more details?

    2. Add 2 json objects according to keys in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String[] args) { String str1 = "{\"a\":{\"num1\":5},\"b\":{\"num1\":8}}"
      2. String str2 = "{\"a\":{\"num2\":7},\"b\":{\"num2\":9}}"
      3. try { JSONObject str1Json = new JSONObject(str1)
      4. JSONObject str2Json = new JSONObject(str2)
      5. List<JSONObject> list = Arrays.asList(str1Json, str2Json)
      6. JSONObject storage = new JSONObject()
      7. JSONObject storageA = new JSONObject()
      8. JSONObject storageB = new JSONObject()
      9. JSONObject a
      10. JSONObject b
      11. JSONObject obj
      12. for(int i=1
      13. i<= list.size()
      14. i++){ obj = list.get(i-1)
      15. a = obj.getJSONObject("a")
      16. b = obj.getJSONObject("b")
      17. storageA.put("num"+i, a.getInt("num"+i))
      18. // we don't want build list storageB.put("num"+i, b.getInt("num"+i))
      19. } storage.put("a", storageA)
      20. storage.put("b", storageB)
      21. System.out.println(storage.toString())
      22. } catch (JSONException e1) { }}

    3. Loading data from sharedpreference (JSON Array)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String[] debtName = new String[3]
      2. SharedPreferences prefs = getSharedPreferences("com.douglasdrumond.test.prefs", Context.MODE_PRIVATE)
      3. String jsonString = prefs.getString("com.douglasdrumond.test.debtName", null)
      4. if (jsonString != null) { JSONArray jsonArray
      5. try { jsonArray = new JSONArray(jsonString)
      6. for (int i = 0
      7. i < jsonArray.length()
      8. i++) { debtName[i] = jsonArray.optString(i)
      9. } } catch (JSONException e) { }}

    4. How to deserialize only some fields in JSON?

      If you need one field only use JSONObject. Output . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import org.json.JSONException
      2. import org.json.JSONObject
      3. public class Main { public static void main(String[] args) throws JSONException { String str = "{" + " \"result\": {" + " \"name1\": \"value1\"," + " \"name2\": \"value2\"," + " }," + " \"wantedName\": \"wantedValue\"" + "}"
      4. JSONObject jsonObject = new JSONObject(str)
      5. System.out.println(jsonObject.getString("wantedName"))
      6. }

      Positive Reactions
      1. It worked!
      Other Reactions
      1. posted example above.
      2. BTW, do you know if it's possible using Gson?

    5. Issues with AsyncTask and Network Loss

      You're getting the nullPointerException because you're expecting a JSON response but since you have no network there is no response to parse. One way to prevent this code from running is to simply place a null check before you go into the loop If it were me I'd check for network connectivity before executing the code. details

      Reactions - Positive 2, Negative 1, Others 0

      1. if(json != null){ for (int i = 0
      2. i < json.length()
      3. i++) { try { JSONObject c = json.getJSONObject(i)
      4. String parsed_results_formatted_address = c .getString("formatted_address")
      5. arrfortextviews.add(parsed_results_formatted_address)
      6. } catch (JSONException e) { e.printStackTrace()
      7. } }}

      Positive Reactions
      1. Thank you !
      2. Glad I was able to help you!.
      Negative Reactions
      1. No problem!
      Other Reactions
      1. !.
      2. This is the approach i was thinking.

    6. Remove duplicates from a Json String in Java?

      keep last value for multiple keys). Modified Class Main method . details

      Reactions - Positive 3, Negative 0, Others 0

      1. import org.json.JSONException
      2. import org.json.JSONObject
      3. public class JSONObjectIgnoreDuplicates extends JSONObject { public JSONObjectIgnoreDuplicates(String json) { super(json)
      4. } public JSONObject putOnce(String key, Object value) throws JSONException { Object storedValue
      5. if (key != null && value != null) { if ((storedValue = this.opt(key)) != null ) { if(!storedValue.equals(value)) //Only through Exception for different values with same key throw new JSONException("Duplicate key \"" + key + "\"")
      6. else return this
      7. } this.put(key, value)
      8. } return this
      9. }}

      Positive Reactions
      1. Excactly!
      2. Just updated my answer as well to include the code.
      3. Thanks, will do it now!.
      Other Reactions
      1. Maybe inherit your modified class from JSONObject and overwrite just putOnce(...), then use the inherited object?
      2. I'm doing that right now...
      3. Not sure which version you have though, JSONObject was updated 3 months ago but putOnce doesn't seem to have changed: URL_https://github.com/douglascrockford/JSON - java/archive/master.zip.

    7. Can't get Value from JSON object using a valid Key

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Exception in thread "main" org.json.JSONException: JSONObject["street_name"] not found.at org.json.JSONObject.get(JSONObject.java:498)at org.json.JSONObject.getString(JSONObject.java:669)at test.Main.main(Main.java:11)

    8. combine two Map String into JSON

      Here is JSON String what I expected And Here is the JAVA codes but I didn't make it successful The challenge is how to combine the two map string that are not at the same level.My code result is Can someone help me with it. Here is the code that u want the output will be Use JSONObject instead of Map if u need JSONArray u can use that also. details

      Reactions - Positive 5, Negative 0, Others 0

      1. public static String BuildJson() throws JSONException { JSONObject map1 = new JSONObject()
      2. map1.put("startDate", "2013-01-01")
      3. map1.put("endDate", "2013-02-01")
      4. map1.put("columns", "mode , event")
      5. JSONObject map2 = new JSONObject()
      6. map2.put("selectionType", "smart")
      7. map2.put("selectionMatch", "123456789012")
      8. map1.put("selection",map2)
      9. System.out.println(map1.toString())
      10. return null
      11. }

      Positive Reactions
      1. Thank you so much, It spent me lots of time.
      2. If it works, pls mark as correct answer.
      3. It works!
      4. thanks.
      5. Done, marked!
      Other Reactions
      1. I am not familiar with JSONObject, so now you give me exactly right direction, I am going to browse the api.

    9. Iterate Json data from web service in correct order

      Enjoy. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String s = "{ \"15:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"16:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"17:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"18:00\":{\"type\":1,\"status\":\"1\",\"appointment_id\":5}}"
      2. try { JSONObject jobj = new JSONObject(s)
      3. Iterator iter = jobj.keys()
      4. while(iter.hasNext()){ String appointmentTime = String.valueOf(iter.next())
      5. aRRaY.add(appointmentTime)
      6. } Collections.sort(aRRaY)
      7. for(String key : aRRaY){ JSONObject appointmentDetails = jobj.getJSONObject(key)
      8. System.out.println(key +" ----- "+appointmentDetails)
      9. } } catch (JSONException e) { e.printStackTrace()
      10. }

    10. HTTPResponse as JSON in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. final JSONObject arr=new JSONObject()
      2. for (int i=0
      3. i<contactStatus.size()
      4. i++){ ContactStatus contactObject=contactStatus.get(i)
      5. try { arr.put(String.valueOf(i),toJson(value1,value2,,value3))
      6. } catch (JSONException e) {catch block e.printStackTrace()
      7. } } //Here we serialize the stream to a String. final String output = arr.toString()
      8. response.setContentLength(output.length())
      9. out.print(output)
      10. //out is object of servlet output stream.

    11. HTTPResponse as JSON in Java

      BABHAHIA . if you want to send jsonObjects from server suppose tomcat server For server side creating jsonobjects I have Called toJson for creating jsonobjects this is the implementation so your jsonobjects are ready for sending we write these objects to ServletoutputStream. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException{JSONObject contactObject = new JSONObject()
      2. contactObject.put("id", id)
      3. contactObject.put("status", value1)
      4. contactObject.put("distance", value2)
      5. contactObject.put("relation", value3)
      6. return contactObject

    12. concat multiple JSONObjects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * Merge "source" into "target". If fields have equal name, merge them recursively. * @return the merged object (target). */public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException { for (String key: JSONObject.getNames(source)) { Object value = source.get(key)
      2. if (!target.has(key)) { // new value for "key": target.put(key, value)
      3. } else { // existing value for "key" - recursively deep merge: if (value instanceof JSONObject) { JSONObject valueJson = (JSONObject)value
      4. deepMerge(valueJson, target.getJSONObject(key))
      5. } else { target.put(key, value)
      6. } } } return target
      7. }/** * demo program */public static void main(String[] args) throws JSONException { JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}")
      8. JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}")
      9. System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b))
      10. // prints: // {"accept":true,"offer":{"issue1":"value1"}} + {"reject":false,"offer":{"issue2":"value2"}} = {"reject":false,"accept":true,"offer":{"issue1":"value1","issue2":"value2"}}}

    13. Android how to sort JSONArray of JSONObjects

      Otherwise the logic is sound. . details

      Reactions - Positive 0, Negative 1, Others 0

      1. Collections.sort( jsonValues, new Comparator<JSONObject>() { @Override public int compare(JSONObject a, JSONObject b) { String valA = new String()
      2. String valB = new String()
      3. try { valA = (String) a.get("keyOfValueToSortBy")
      4. valB = (String) b.get("keyOfValueToSortBy")
      5. } catch (JSONException e) { Log.e(LOG_TAG, "JSONException in combineJSONArrays sort section", e)
      6. } int comp = valA.compareTo(valB)
      7. if(comp > 0) return 1
      8. if(comp < 0) return -1
      9. return 0
      10. }})

      Negative Reactions
      1. Yes you are right the if ... return is unnecessary.
      Other Reactions
      1. Couldn't you just return valA.compareTo(valB)?

    14. Creating JSONObject from string in JAVA (org.json)

      n specifies a newline character i'm not sure exactly why it breaks the parser but adding a to it will espace the control character. works fine. details

      Reactions - Positive 9, Negative 2, Others 0

      1. @Testpublic void test() throws JSONException { String s = "{\"hours\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\"],\"lessons\":[\"\u05d2\u05d9\u05d0,\u05ea\u05dc\u05de,\u05e2\u05e8\u05d1,\u05e4\u05d9\u05e1,\u05d1\u05d9\u05d5,\n\u05d6\u05d9\u05d5,\u05d5\u05d9\u05d9,\u05dc\u05d5\u05d9,\u05e4\u05d1\u05dc,\u05e8\u05d9\u05d9,\",\"\u05d2\u05d9\u05d0,\u05ea\u05dc\u05de,\u05e2\u05e8\u05d1,\u05e4\u05d9\u05e1,\u05d1\u05d9\u05d5,\n\u05d6\u05d9\u05d5,\u05d5\u05d9\u05d9,\u05dc\u05d5\u05d9,\u05e4\u05d1\u05dc,\u05e8\u05d9\u05d9,\",\"\u05d7\u05e0\\\"\u05d2 \u05d1\u05e0\u05d9\u05dd,\u05d7\u05e0\\\"\u05d2 \u05d1\u05e0\u05d5\u05ea\n\u05d9\u05de\u05e4\u05d5\u05dc\u05e1\u05e7\u05d9 \u05dc,\u05e0\u05d0\u05d5\u05e8 \u05de\u05dc\u05d9\",\"\u05e1\u05e4\u05e8\u05d5\u05ea\n\u05d6\u05d9\u05dc\u05d3\u05de\u05df \u05d0\u05d5\u05e8\u05dc\u05d9\",\"\u05d0\u05e0\u05d2\u05dc\u05d9\u05ea\n\u05d1\u05e9\u05d9 \u05e9\u05d5\u05dc\u05de\u05d9\u05ea\",\"\u05d0\u05e0\u05d2\u05dc\u05d9\u05ea\n\u05d1\u05e9\u05d9 \u05e9\u05d5\u05dc\u05de\u05d9\u05ea\",\"\u05ea\u05e0\\\",\u05e2\u05e8\u05d1,\u05e6\u05e8\u05e4,\u05e7\u05d5\u05dc,\u05d1\u05d9\u05d5,\n\u05e9\u05d7\u05e3,\u05de\u05d6\u05dc,\u05dc\u05e1\u05e7,\u05d8\u05d5\u05e4,\u05dc\u05d5\u05d9,\",\"\u05ea\u05e0\\\",\u05e2\u05e8\u05d1,\u05e6\u05e8\u05e4,\u05e7\u05d5\u05dc,\u05d1\u05d9\u05d5,\n\u05e9\u05d7\u05e3,\u05de\u05d6\u05dc,\u05dc\u05e1\u05e7,\u05d8\u05d5\u05e4,\u05dc\u05d5\u05d9,\",\"\u05e2\u05e8\u05d1,\u05e7\u05d5\u05dc,\u05d1\u05d9\u05d5,\u05d8\u05db\\\",\u05e8\u05d5\u05e1,\n\u05dc\u05d5\u05d9,\u05e7\u05de\u05d7,\u05d1\u05e1\u05d5,\u05d5\u05e7\u05e1,\u05e6\u05d5\u05e8,\",\"\u05e2\u05e8\u05d1\u05d9,\u05e7\u05d5\u05dc\u05e0,\u05d1\u05d9\u05d5\u05d8,\u05d8\u05db\\\"\u05dd\n\u05dc\u05d5\u05d9,\u05d1\u05e1\u05d5\u05df,\u05d5\u05e7\u05e1,\u05e6\u05d5\u05e8\",\"\"]}"
      2. s= s.replaceAll("\n", "\\n")
      3. JSONObject json = new JSONObject(s)
      4. }

      Positive Reactions
      1. Wow, it is working but when I tried to implement it on my own code, it didn't.
      2. I'm going to give you my code, you can't believe how much time I'm stuck on this issue here, I'll be very glad if you would help me.
      3. Can you please explain me why you switch the /n to //n?
      4. Post the stacktrace please.
      5. I really thank you deeply I would never guess it was the problem.
      6. Again, I'm very thankfull for your help.
      7. yes it works for me just fine.
      8. Updated my question once again, thank you for your help.
      9. ok works in my test.
      Negative Reactions
      1. and why the hell these services add random characters?
      2. Sorry, it really works, I guess I was just tired or something..
      Other Reactions
      1. I've added that line right after the replace function, and still same issue for me..
      2. It really works for you?

    15. Creating JSONObject from string in JAVA (org.json)

      Again I'm very thankfull for your help. Output is "hours":["1","2","3","4","5","6","7","8","9","10","11"] . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import org.json.JSONException
      2. import org.json.JSONObject
      3. public class JSONTest {
      4. public static void main(String[] args) throws JSONException {
      5. String s = "{\"hours\"[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\"]}"
      6. JSONObject jsonobject = new JSONObject(s)
      7. System.out.println(jsonobject)
      8. }
      9. }

      Positive Reactions
      1. Great, it works actually, but can you look at "EDIT 2" (in my question above) that is the real string that I'm trying to convert to jsonobject.
      Other Reactions
      1. Actually if I could conver a stream to a jsonobject it would be much better because I get that string from a server.

    16. How can I fetch the value from JSON in Java program?

      In this answer I'll assume that you want to get at that pageid value. Let's only assume the existence of pageid in the nesting at a specific level Your JSON input seems peculiar in that the first nested object has a pages field that contains another object. details

      Reactions - Positive 0, Negative 0, Others 0

      1. // "query" is the top-level object: JSONObject query = json.getJSONObject("query")
      2. // "pages" is a field of "query"JSONObject pages = query.getJSONObject("pages")
      3. // these will hold the object with the value that you want, and that value:JSONObject nestedObject = null
      4. int pageId = 0
      5. // these are the property names in the "pages" object:String[] keys = pages.getNames(pages)
      6. // iterate over the keys in the "pages" object, looks for JSONObjects:for (int i = 0
      7. i < keys.length
      8. i++){ try { nestedObject = pages.getJSONObject(keys[i])
      9. // only consider objects with a "pageid" key, stop at the first one: if (nestedObject.has("pageid")) break
      10. } catch (JSONException je) {
      11. }}if (nestedObject != null) pageId = nestedObject.getInt("pageid")

    17. Parsing JSON in J2ME

      ). You can parse the JSON string by the following example . details

      Reactions - Positive 1, Negative 1, Others 0

      1. public CustomerInfo(String jsonTxt) { try { JSONObject json= (JSONObject) new JSONTokener(jsonTxt).nextValue()
      2. test = (String) json2.get("displayName")
      3. } catch (JSONException e) { e.printStackTrace()
      4. }}

      Positive Reactions
      1. Thanks much, looks cleaner than what I was trying.
      Negative Reactions
      1. I think I've solved the problem.
      Other Reactions
      1. Then accept the answer :).
      2. It was more me, not reading the JSON structure right.

    18. Compare two JSON objects in Java

      Also given that I use this in unit tests I didn't put effort into optimizations. Here it is . details

      Reactions - Positive 4, Negative 1, Others 0

      1. public static boolean jsonObjsAreEqual (JSONObject js1, JSONObject js2) throws JSONException { if (js1 == null || js2 == null) { return (js1 == js2)
      2. } List<String> l1 = Arrays.asList(JSONObject.getNames(js1))
      3. Collections.sort(l1)
      4. List<String> l2 = Arrays.asList(JSONObject.getNames(js2))
      5. Collections.sort(l2)
      6. if (!l1.equals(l2)) { return false
      7. } for (String key : l1) { Object val1 = js1.get(key)
      8. Object val2 = js2.get(key)
      9. if (val1 instanceof JSONObject) { if (!(val2 instanceof JSONObject)) { return false
      10. } if (!jsonObjsAreEqual((JSONObject)val1, (JSONObject)val2)) { return false
      11. } } if (val1 == null) { if (val2 != null) { return false
      12. } } else if (!val1.equals(val2)) { return false
      13. } } return true
      14. }

      Positive Reactions
      1. point taken :) Hope that it doesn't get too much votes though, otherwise it's gonna be lots of support.
      2. It happens to the best of us also :).
      3. Thank you Sean, fixed it.
      4. Since you mentioned optimizations :), if val1 is null you will get a NullPointerException from this code if (!val1.equals(val2)) {.
      Negative Reactions
      1. this is embarrassing.
      Other Reactions
      1. You did not consider if js2 is null or not when js1 is not null.
      2. +1 for fixing it in your answer.

    19. How to check whether a given string is valid JSON in Java

      has links to very many parsers. A wild idea try parsing it and catch the exception . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public boolean isJSONValid(String test){ try { new JSONObject(test)
      2. return true
      3. } catch(JSONException ex) { return false
      4. }}

      Positive Reactions
      1. this one should be the correct answer.
      Other Reactions
      1. It is close, but is missing a validation for a JSONArray (i've updated this post with a more suitable function).

    20. When JsonObject's keys are iterated they aren't in the same order as in the response from the server

      You can use Sorted map to put keys and values into. Something like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static List listFromJsonSorted(JSONObject json) { if (json == null) return null
      2. SortedMap map = new TreeMap()
      3. Iterator i = json.keys()
      4. while (i.hasNext()) { try { String key = i.next().toString()
      5. JSONObject j = json.getJSONObject(key)
      6. map.put(key, j)
      7. } catch (JSONException e) { e.printStackTrace()
      8. } } return new LinkedList(map.values())
      9. }

    21. JSON String tidy/formatter for Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(final String[] args) throws JSONException{ final JSONObject obj = new JSONObject("{\"glossary\":{\"title\": \"example glossary\", \"GlossDiv\":{\"title\": \"S\", \"GlossList\":{\"GlossEntry\":{\"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\":{\"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"]}, \"GlossSee\": \"markup\"}}}}}")
      2. System.out.println(JsonFormatter.format(obj))
      3. }

    22. How can add JSON array into Google App datastore

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * Sets the properties of the specified entity by the specified json object. * * @param entity the specified entity * @param jsonObject the specified json object * @throws JSONException json exception */public static void setProperties(final Entity entity, final JSONObject jsonObject) throws JSONException { @SuppressWarnings("unchecked") final Iterator<String> keys = jsonObject.keys()
      2. while (keys.hasNext()) { final String key = keys.next()
      3. final Object value = jsonObject.get(key)
      4. if (!GAE_SUPPORTED_TYPES.contains(value.getClass()) && !(value instanceof Blob)) { throw new RuntimeException("Unsupported type[class=" + value. getClass().getName() + "] in Latke GAE repository")
      5. } if (value instanceof String) { final String valueString = (String) value
      6. if (valueString.length() > DataTypeUtils.MAX_STRING_PROPERTY_LENGTH) { final Text text = new Text(valueString)
      7. entity.setProperty(key, text)
      8. } else { entity.setProperty(key, value)
      9. } } else if (value instanceof Number || value instanceof Date || value instanceof Boolean || GAE_SUPPORTED_TYPES.contains(value.getClass())) { entity.setProperty(key, value)
      10. } else if (value instanceof Blob) { final Blob blob = (Blob) value
      11. entity.setProperty(key, new com.google.appengine.api.datastore.Blob( blob.getBytes()))
      12. } }}

    23. Passing JSON object

      You can see the constructor right in the source-for-JSONObject.java . . details

      Reactions - Positive 1, Negative 1, Others 0

      1. /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp
      2. <small>(left brace)</small> and ending * with <code>}</code>&nbsp
      3. <small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source * string or a duplicated key. */public JSONObject(String source) throws JSONException { this(new JSONTokener(source))
      4. }

      Positive Reactions
      1. Actually I searched the internet and found another jar that is having the number of constructors found in the documentation of JSONLink is this: URL_http://code.google.com/p/wave-robot-java - client/downloads/detail?name=json.jar&can=4&q=So in order to use JSON correctly we have to include two jars namely the one we get from JSON website and one getting from Google website(Link given) While using we have to specifically tell the compiler whose constructor we want to call.
      Negative Reactions
      1. Oops, my bad.
      Other Reactions
      1. @RyanStewart: [Yes it does.
      2. ]( URL_http://www.json.org/javadoc/org/json/JSONObject.h tml#JSONObject(java.lang.String)).
      3. URL_http://www.json.org/javadoc/org/json/JSONObject.htmllook at this.
      4. I never noticed it hiding among those others.
      5. If you look at the docs, that JSONObject doesn't have a JSONObject(String) constructor, either.

    24. How to parse with GSON when identifier has space in name

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String parse = "{\"Person Id\":\"test\",\"Last Name\": \"lname\",\"First Name\":\"fname\"}"
      2. try { JSONObject jsonObject = new JSONObject(parse)
      3. String id = jsonObject.getString("Person Id")
      4. System.out.println("id="+id)
      5. System.out.println("lname="+jsonObject.getString("Last Name"))
      6. System.out.println("fname="+jsonObject.getString("First Name"))
      7. } catch (JSONException e) { e.printStackTrace()
      8. }

    25. How to POST data to server in JSON format

      Thilo nop that does not have stuff about how 2 form json string. I struglled but then i did it myself and this is how we can send json data to server. details

      Reactions - Positive 3, Negative 1, Others 0

      1. JSONObject returnedJObject= new JSONObject()
      2. JSONObject KeyvalspairJObject=new JSONObject ()
      3. JSONObject devcKeyvalspairJObject=new JSONObject ()
      4. JSONObject capabilityJObject=new JSONObject()
      5. JSONObject ScreenDimensionsJObject =new JSONObject()
      6. JSONObject deviceJObject= new JSONObject()
      7. try{ KeyvalspairJObject.put("key1","val1")
      8. KeyvalspairJObject.put("key2","val2")
      9. capabilityJObject.put("sms", false)
      10. capabilityJObject.put("data", true)
      11. capabilityJObject.put("gps", true)
      12. capabilityJObject.put("wifi", true)
      13. capabilityJObject.put("keyValue", KeyvalspairJObject)
      14. ScreenDimensionsJObject.put("width", 45)
      15. ScreenDimensionsJObject.put("height", 45)
      16. devcKeyvalspairJObject.put("Devckey1","val1")
      17. devcKeyvalspairJObject.put("DEVCkey2","val2")
      18. deviceJObject.put("userAgent", "MYUserAgent")
      19. deviceJObject.put("capabilities", capabilityJObject)
      20. deviceJObject.put("screen", ScreenDimensionsJObject)
      21. deviceJObject.put("keyValue", devcKeyvalspairJObject)
      22. returnedJObject.put("clientId", "ID:1234-1234")
      23. returnedJObject.put("carrier","TMobile")
      24. returnedJObject.put("device",deviceJObject)
      25. returnedJObject.put("time",1294617435)
      26. returnedJObject.put("msisdn","1234567890")
      27. returnedJObject.put("timezone","GMT")
      28. } catch(JSONException e) { }

      Positive Reactions
      1. but thanks for pointing that out.
      2. And if you are receiving code 200 then it must be success response from server.
      3. yes but the response I get means the server didn't got any input, I'll try to talk to the guy working on the API (the problem must be there) but he didn't answered my emails today.
      Negative Reactions
      1. Also for me it's not working I get "no input data" from the server with code 200.
      Other Reactions
      1. 200 stands for "status ok".
      2. Using other name will not break the code ;).
      3. ya may be server guys can give you more insight on this.
      4. doesn't it represent the object that needs to be sent?
      5. just to make below code in sync with above code i used returnedJObject.
      6. why is the jsonObj parameter in putData called returnedJObject?

    26. Sending JSONP vs. JSON data?

      So you must specify the callback name. So your function might look like this . details

      Reactions - Positive 3, Negative 0, Others 0

      1. private static String getJSONPObject(String callback, String s) throws JSONException { return callback + "(" + new JSONObject(s) + ")"
      2. }

      Positive Reactions
      1. ah, thanks, i understand the callback now.
      2. thanks for the clarification, JP!.
      3. i could ask for it as a parameter in my function, but that doesn't seem as user friendly as being able to parse it in the link as Abdullah exemplified.
      Other Reactions
      1. specifically, this is used inside a class, and the web service allows one to access these methods.
      2. You should have access to the http request object or at least some way of accessing the callback which was sent, usually in this form: URL_http://example.com?callback=name123 .
      3. example.com?callback=name123 would call your JSP servlet which in turn calls the function "getJSONPObject" and passes "name123" as the "callback" parameter.
      4. Ya, and to expand upon Abdullah's point, your Javascript code should then call the function "name123" to get the JSON.
      5. however, i'm unsure as to how to retrieve it in the web service.
      6. can the request object be used inside the class?

    27. Convert JSON query parameters to objects with JAX-RS

      Since all it appears that the JSONParam does is wrap the DataTransferObject and use a String based constructor would it be possible to just add a String based constructor to the DataTransferObject'. Adding to Jason's solution using courtesy of Crockford) Don't re-invent the wheel . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.JSONObject
      2. public class JSONParam { private DataTransferObject dto
      3. public JSONParam(String json) throws WebApplicationException { try { // convert json string DataTransferObject and set dto JSONObject jo = new JSONObject(json)
      4. dto.setParamA(jo.getString("paramA"))
      5. dto.setParamB(jo.getString("paramB"))
      6. // There are other get methods for Integer, Double, etc. // You can also build JSON from Java objects. } catch (JSONException e) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST) .entity("Couldn't parse JSON string: " + e.getMessage()) .build())
      7. } } public DataTransferObject getDTO() { return dto
      8. } }

      Other Reactions
      1. But you can use the version that lili is suggesting ([lili]( URL_http://stackoverflow.com/a/6250744/853510)) .
      2. If you don't pass your JSON object via parameter, you cant use this solution.

    28. Cannot parse and display non-utf8 characters read from an http request

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.json.public class JsonTest extends TestCase { public void testParseText() { try { JSONObject json1 = new JSONObject("{\"a\":\"\u05dd\"}")
      2. // \u05dd is a Hebrew character JSONObject json2 = new JSONObject("{\"a\":\"\\u05dd\"}")
      3. // \u05dd is a Hebrew character System.out.println(json1.toString())
      4. System.out.println(json2.toString())
      5. } catch (JSONException e) { e.printStackTrace()
      6. } }}

  7. Android REST API connection

    None .. details

    1. public class MainActivity extends Activity {
    2. @Override
    3. protected void onCreate(Bundle savedInstanceState) {
    4. super.onCreate(savedInstanceState)
    5. setContentView(R.layout.activity_main)
    6. Button button = (Button) findViewById(R.id.btn)
    7. button.setOnClickListener(
    8. new View.OnClickListener() {
    9. @Override
    10. public void onClick(View v) {
    11. String url = "http://date.jsontest.com"
    12. new MyAsyncTask().execute(url)
    13. }
    14. })
    15. }
    16. class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
    17. @Override
    18. protected JSONObject doInBackground(String... urls) {
    19. return RestService.doGet(urls[0])
    20. }
    21. @Override
    22. protected void onPostExecute(JSONObject jsonObject) {
    23. TextView tv = (TextView) findViewById(R.id.txtView)
    24. tv.setText(jsonObject.toString())
    25. }
    26. }
    27. }

  8. Android REST API connection

    In many application I used AsyncTask to communicate with API and IMO AsyncTask approach have a lot benefits. Here is example of AsyncTask which gets the JSON data over the API You have to post your code and point to problem then SO users can help you. .. details

    1. private class EventsAsyncTask extends AsyncTask<GetRequest, String, JSONObject> { @Override protected JSONObject doInBackground(GetRequest... params) { JSONObject data = null
    2. GetRequest eventRequest = params[0]
    3. if (eventRequest instanceof GetRequest) { DefaultHttpClient httpClient = HttpClient.getHttpClientInstance()
    4. try { HttpGet httpGet = HttpClient.getHttpGetInstance()
    5. httpGet.setURI(eventRequest.getUriString())
    6. httpGet.setHeader("Content-type", "application/json")
    7. HttpResponse httpResponse = httpClient.execute(httpGet)
    8. //Check is authentication to the server passed if (httpResponse.getStatusLine().getStatusCode() == 401) { // do some actions to clear userID, token etc ... // finish finish()
    9. } HttpEntity responseEntity = httpResponse.getEntity()
    10. if (responseEntity instanceof HttpEntity) data = new JSONObject(EntityUtils.toString(responseEntity))
    11. responseEntity.consumeContent()
    12. } catch (ClientProtocolException CPException) { //set data to null, handle and log CPException } catch (IOException ioException) { //set data to null, handle and log IOException } catch (JSONException jsonException) { //set data to null, handle and log JSONException } catch (URISyntaxException useException) { //set data to null, handle and log URISyntaxException } } return data
    13. } }

  9. When using JSON in Fragments the app is not responding in Android Development

    None .. details

    1. class TheTask extends AsyncTask<String, String, String> {
    2. @override
    3. protected String doInbackground(String... params) {
    4. String _response = null
    5. try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
    6. HttpPost httpPost = new HttpPost(params[0])
    7. HttpResponse httpResponse = httpClient.execute(httpPost)
    8. HttpEntity httpEntity = httpResponse.getEntity()
    9. _response = EntityUtils.toString(httpEntity)
    10. } catch (Exception e) {
    11. e.printStacktrace()
    12. }
    13. return _response
    14. }
    15. @Override
    16. protected void onPostExecute(
    17. String result) { // TODO Auto-generated method stub super.onPostExecute(result)
    18. Log.i(".......", result)
    19. }
    20. }

  10. How to efficiently map a org.json.JSONObject to a POJO?

    So instead of using the readValue method that accepts a String you'd use sterxml/jackson/databind/ObjectMapper.html#readValue%28com.fasterxml.jackson.c ore.JsonParser,%20java.lang.Class%29 this-version that accepts a JsonParser JSON is a very simple format so it should not be hard to create the convertJsonFormat by hand. Here's my attempt Note that while the Jackson's JsonNode can represent some extra types such as BigInteger Decimal etc they are not necessary since the code above covers everything that JSONObject can represent. .. details

    1. static JsonNode convertJsonFormat(JSONObject json) { ObjectNode ret = JsonNodeFactory.instance.objectNode()
    2. @SuppressWarnings("unchecked") Iterator<String> iterator = json.keys()
    3. for (
    4. iterator.hasNext()
    5. ) { String key = iterator.next()
    6. Object value
    7. try { value = json.get(key)
    8. } catch (JSONException e) { throw new RuntimeException(e)
    9. } if (json.isNull(key)) ret.putNull(key)
    10. else if (value instanceof String) ret.put(key, (String) value)
    11. else if (value instanceof Integer) ret.put(key, (Integer) value)
    12. else if (value instanceof Long) ret.put(key, (Long) value)
    13. else if (value instanceof Double) ret.put(key, (Double) value)
    14. else if (value instanceof Boolean) ret.put(key, (Boolean) value)
    15. else if (value instanceof JSONObject) ret.put(key, convertJsonFormat((JSONObject) value))
    16. else if (value instanceof JSONArray) ret.put(key, convertJsonFormat((JSONArray) value))
    17. else throw new RuntimeException("not prepared for converting instance of class " + value.getClass())
    18. } return ret
    19. }static JsonNode convertJsonFormat(JSONArray json) { ArrayNode ret = JsonNodeFactory.instance.arrayNode()
    20. for (int i = 0
    21. i < json.length()
    22. i++) { Object value
    23. try { value = json.get(i)
    24. } catch (JSONException e) { throw new RuntimeException(e)
    25. } if (json.isNull(i)) ret.addNull()
    26. else if (value instanceof String) ret.add((String) value)
    27. else if (value instanceof Integer) ret.add((Integer) value)
    28. else if (value instanceof Long) ret.add((Long) value)
    29. else if (value instanceof Double) ret.add((Double) value)
    30. else if (value instanceof Boolean) ret.add((Boolean) value)
    31. else if (value instanceof JSONObject) ret.add(convertJsonFormat((JSONObject) value))
    32. else if (value instanceof JSONArray) ret.add(convertJsonFormat((JSONArray) value))
    33. else throw new RuntimeException("not prepared for converting instance of class " + value.getClass())
    34. } return ret
    35. }

    Positive Reactions
    1. Thanks!.
    2. I've tried it out and it works.
    Other Reactions
    1. According to my benchmarks, it has a performance gain of about 30%.

    • See Also (9)
    1. Loading data from sharedpreference (JSON Array)

      based on the public static JSONArray loadJSONArray how would I retrieve the JSONArray. To retrieve the data back into arrays you have to iterate over the JSONArray For clarification here's the code I used for testing In MainAcitivity In SecondActivity . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jsonString = prefs.getString("key", null)
      2. if (jsonString != null) { JSONArray jsonArray
      3. try { jsonArray = new JSONArray(jsonString)
      4. for (int i = 0
      5. i < jsonArray.length()
      6. i++) { debtName[i] = jsonArray.optString(i)
      7. } } catch (JSONException e) { }}

      Other Reactions
      1. it's not returning any values, though it is not providing an error either.
      2. Is the jsonString empty or null?

    2. Can't get Value from JSON object using a valid Key

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Exception in thread "main" org.json.JSONException: JSONArray[2] not found.at org.json.JSONArray.get(JSONArray.java:234)at org.json.JSONArray.getJSONObject(JSONArray.java:326)at test.Main.main(Main.java:11)

    3. How to verify given string is valid JsonArray using a net.sf.json library

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public boolean isValid(String jsonString){ boolean valid = false
      2. try { JSONArray.fromObject(jsonString) valid = true
      3. } catch(JSONException ex) { valid = false
      4. } return valid
      5. }

    4. How to verify given string is valid JsonArray using a net.sf.json library

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public XXX parseYourString(String json) { XXX xxx = new XXX()
      2. try { JSONArray arr = JSONArray.fromObject(json)
      3. // do something with arr } catch (JSONException ex) { return null
      4. } return xxx
      5. }

    5. How to verify given string is valid JsonArray using a net.sf.json library

      What I am trying to say you don't need special check if this string is valid. You have two solutions or . details

      Reactions - Positive 0, Negative 2, Others 0

      1. public XXX parseYourString(String json) throws net.sf.json.JSONException { JSONArray arr = JSONArray.fromObject(json)
      2. // do something with arr and return custom result}

      Negative Reactions
      1. You just need to handle this exception and make some decision to return null, or throw exception by your method (and handle later).
      2. You don't really need to make special check if this is valid string because you receive this information from exception.
      Other Reactions
      1. though you are right but only when i know string is valid array, what if get that string as method arguement.please see my edit.
      2. that solution is provided by @Ankur Lathi.I am looking for solution using this API rather than making decision on basis of exception.Though i think so it is the only approach left.
      3. edited.

    6. Java String conversion to JSON can not be done

      I've coded like this. See the LogCat . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONArray users = null
      2. String jsStr = "[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele@pele.com\",\"password\":\"\"}, {\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]"
      3. try { users = new JSONArray(jsStr)
      4. } catch (JSONException e) { e.printStackTrace()
      5. }Log.v("JSONStr", String.valueOf(users.length()))
      6. for(int i = 0
      7. i<users.length()
      8. i++){ try { Log.v("Name", users.getJSONObject(i).getString("name"))
      9. } catch (JSONException e) { e.printStackTrace()
      10. }}

      Positive Reactions
      1. It is very interesting.
      2. Your example working for me in the same method.
      Other Reactions
      1. But my json from the server can not be parsed, even he is looking the same as your string above (jsStr).
      2. did you try and trim the string before parsing it?
      3. Hmm very peculiar I've used many dot net services with the same logic.
      4. maybe my json (my string) has some covered character which I can not see.

    7. Parsing error from string to JSONArray in Android Application

      every entry of your json array is an jsonobject. So and you do this for every entry of your json object. details

      Reactions - Positive 4, Negative 3, Others 0

      1. try { JSONArray jArray = new JSONArray(result)
      2. for(int i=0
      3. i<jArray.length()
      4. i++) { json_data = jArray.getJSONObject(i)
      5. articleId = json_data.optInt("ID")
      6. title = json_data.optString("NAME")
      7. } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString())
      8. }

      Positive Reactions
      1. Thanks for reply!I check your functin "copyInStringBuilder", but how do you use the "buffer" var?
      2. It's a bit strange, I got a simple JSONArray and when I set a breakpoint in the function for the JSON data, my program dont get in the for() and it goes directly in the catch() function.But the "result" var containts the right JSON String.
      3. Hi!
      4. my best guess?
      Negative Reactions
      1. I'm seeing the same weird exception on Android 2.3 (4.0 seems to work).
      2. The error is how you read the InputStream in order to "create" the String result you pass to the JSONArray jArray new JSONArray(result);.
      3. Yes, thats true, but I can't even convert the String to a JSONArray.I tested my code with a other JSON PHP File with other entrys and there was no error, only with this code and I dont know why.The program reaches only the line "JSONArray jArray new JSONArray(result);" and then it aborts in the for and catches this error:Here is the error code from LogCat:Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray.I hope you understand my problem!
      Other Reactions
      1. Did you solve this?
      2. Just for the purpose of trying use the method copyInStringBuilder() that I ve added in the post edit and report me some feedback.
      3. See my edit ......
      4. :-).

    8. Concate JSONArray

      I have heard about google-gson library but I don't know whether it can help me or not but I don't want any other dependency in my Android Application. I would try something like this I don't have a compiler right now to test but you can give it a try and see if it works or at least it gives you an idea of how to do it). details

      Reactions - Positive 4, Negative 0, Others 0

      1. private JSONArray concatArray(JSONArray arr1, JSONArray arr2) throws JSONException { JSONArray result = new JSONArray()
      2. for (int i = 0
      3. i < arr1.length()
      4. i++) { result.put(arr1.get(i))
      5. } for (int i = 0
      6. i < arr2.length()
      7. i++) { result.put(arr2.get(i))
      8. } return result
      9. }

      Positive Reactions
      1. useful.
      2. thanks bro!.
      3. Yep that worked!
      4. thanks you !

    9. Concate JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private JSONArray concatArray(JSONArray... arrs) throws JSONException { JSONArray result = new JSONArray()
      2. for (JSONArray arr : arrs) { for (int i = 0
      3. i < arr.length()
      4. i++) { result.put(arr.get(i))
      5. } } return result
      6. }

  11. Android JSON Parsing And Conversion

    Try this. . .. details

    1. String apellidos = jso.getString("Apellidos")
    2. System.out.println(apellidos)
    3. int str2 = jso.getInt("Ao_nacimiento")
    4. System.out.println(str2)
    5. String nombre = jso.getString("Nombre")
    6. System.out.println(nombre)
    7. JSONArray array = jso.getJSONArray("Nombres_Hijos")
    8. for(int i = 0
    9. i < array.length()
    10. i++){ System.out.println(array.get(i))
    11. }

    Positive Reactions
    1. Thank you but I'm getting errors in all the "get" functions: "The method getString(int) in the type JSONArray is not applicable for the arguments (String)", "The method getInt(int) in the type JSONArray is not applicable for the arguments (String)", "The method getJSONArray(int) in the type JSONArray is not applicable for the arguments (String)", and in the .toString function "The method toString(int) in the type JSONArray is not applicable for the arguments (String)".
    2. As per your JSON creation this is correct code.
    Other Reactions
    1. How odd.
    2. Maybe I need to close Eclipse and start it up again?
    3. I am able to parse JSON Object.

    • See Also (79)
    1. JSON - parsing document with JSONArray in Java

      Also where is title a JSONArray. This code should work You have a JSONObject at the root of your JSON string. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONObject jsonObject = (JSONObject) obj
      2. JSONArray msg = (JSONArray) jsonObject.get("items")
      3. Iterator iterator = msg.iterator()
      4. while (iterator.hasNext()) { //System.out.println(iterator.next())
      5. JSONObject item = (JSONObject) iterator.next()
      6. JSONObject item_snippet = (JSONObject) item.get("snippet")
      7. System.out.println( item_snippet.get("title"))
      8. }

      Positive Reactions
      1. Works.
      2. Thanks for help again ;).

    2. JSON - parsing document with JSONArray in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object obj = parser.parse(str)
      2. // str contains the JSON codeJSONObject jsonObject = (JSONObject) obj
      3. JSONArray msg = (JSONArray) jsonObject.get("items")
      4. Iterator iterator = msg.iterator()
      5. while (iterator.hasNext()) { // cast next item to JSONObject JSONObject item = (JSONObject) iterator.next()
      6. // grab the title System.out.println(item.get("title"))
      7. }

    3. Passing json array in a key value pair

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray grades = new JSONArray()
      2. grades.put(mathGrade)
      3. grades.put(scienceGrade)
      4. obj.put("grades", grades)

    4. How to put JSON information in an array to use it for displaying in ListView

      For example since your root is a json array you want to instantiate a JSONArray object from your json data you have. Now from this array you can grab individual JSONObject for each object in your array. details

      Reactions - Positive 6, Negative 1, Others 0

      1. JSONArray jsonArray = new JSONArray(jsonString)

      Positive Reactions
      1. Like one of the JSON array entry won't have the data label or any values there.
      2. Do you mean that your value is just an empty string after parsing the JSON?
      3. You can add a property to a json object by doing something like this: jsonObject.put("data", "some value"); And you could do this after checking the isNull I mentioned before.
      4. I would recommend using Androids AsyncTask to run your network call on a new thread.
      5. But like I said, this may be more than what you need for your application.
      6. jsonObject.isNull("data"); This will return true if there is no mapping for data.
      Negative Reactions
      1. So you can only try to grab a value for data if that returns false.
      Other Reactions
      1. Yeah that would be one approach to do it, if you are looking to expand on this and maybe persist the data you may want to look into storing your data in a database on the phone once you receive it.
      2. What if some of the entry is NO DATA, can I dummy fill it with data?
      3. You can use the isNull method available in the JSONObject to check if there is data there.
      4. I was able to receive the json text and now to extract it.
      5. Eclipse gives me a warning: 11-11 15:26:11.433: W/System.err(9054): org.json.JSONException: No value for dataI am wondering if the any of the label is missing, just fill it with dummy data.
      6. URL_http://developer.android.com/reference/android/os/AsyncTask.html .
      7. jsonString is which variable in my class?
      8. This would be the result you get back from your network call.
      9. Does that help?
      10. Here is my Pastebin: URL_http://pastebin.com/260jvLcx (I am opening up a chat for this).
      11. I have 7 entries but once it received a blank entry it skips everything after.
      12. Also all networking needs to be done on a separate thread and not the UI thread.
      13. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/40980/discussion-between-sikni8-and - dejanristic).
      14. If you look at my full program code, maybe you will have a better understanding of it?
      15. This way where ever you are in your app you could do a query to retrieve the data.
      16. I am thinking I can put it in a Public array which can be accessible by any of the fragments within the activity.
      17. Is there anyway to fill it with dummy, or it just won't be allowed to do that?

    5. Parsing Json Array resulting in This is not a JSON Array exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonArray Jarray = parser.parse(jsonReader).getAsJsonObject().getAsJsonArray("FoodItemData")

    6. Parsing Json Array resulting in This is not a JSON Array exception

      But I don't think it is necessary since Gson uses Reflections to set the fields. You will need to change this to Your JSON contains a JSON object at the root called FoodItemData. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JsonArray Jarray = parser.parse(jsonReader).getAsJsonArray()

      Positive Reactions
      1. Thanks so much!
      2. Got it working.

    7. Parsing Json Array resulting in This is not a JSON Array exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonArray Jarray = (JsonArray) parser.parse(jsonReader).getAsJsonObject().get("FoodItemData")

    8. how to handle json exception occur inside asyntask

      check now i update my full code. I think this occurred due to nullpointerexception you need to handle the nulls explicitly And later also check . details

      Reactions - Positive 3, Negative 1, Others 0

      1. if(allergen!=null){ JSONArray jArray = new JSONArray(allergen)
      2. ......}

      Positive Reactions
      1. whyu write this if(mCursor!=null){??
      2. well its better to check that resultset contains data or not..
      3. i guess its work if(allergen!=null){.
      Negative Reactions
      1. It means that allergen column has null in it... And you are populating the json object from allergen... so that's why you got exception when making json object from (allergen)null....
      Other Reactions
      1. only allergens are null but name description are present.
      2. in my cursor name (mCursor.getString(mCursor.getColumnIndex("name"))); description (mCursor.getString(mCursor.getColumnIndex("description"))); nutrition=(mCursor.getString(mCursor.getColumnIndex("nutrition"))); allergen=(mCursor.getString(mCursor.getColumnIndex("allergen"))); mainimage=(mCursor.getString(mCursor.getColumnIndex("image"))); alergens image nutritiona re null but name and description are present.

    9. Getting a JSON object from a target host. Error: Target host must not be null

      MainActivity.java . I think you're missing the http scheme so instead of put EDIT Even if that will work parsing of JSON will fail because of this line this assumes the response is an array but it's a JSONObject that contains two entries resultsCount and results. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray array = new JSONArray(data)

      Positive Reactions
      1. Thank you very much gunar!.

    10. Parsing String[] Request Parameter through REST with Apache CXF

      For instance I'm now sending the macAddresses as a JSon String "mac1","mac2" from the client. On the server side I convert this JSon string to a String[ using the following method I hope this will help someone out there. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static String[] parseStringArrayFromJSONArray(String jsonArray){ String[] stringArray = null
      2. try { JSONArray array = new JSONArray(jsonArray)
      3. if (array != null) { stringArray = new String[array.length()]
      4. for (int i = 0
      5. i < array.length()
      6. i++) { stringArray[i] = array.getString(i)
      7. } } } catch (Exception e) { stringArray = null
      8. } return stringArray
      9. }

    11. Removing the end [ and ] from php Json result for Android Java code

      Demo or Demo . Instead of using JSonobject use JSONArray Later loop through the array and do the business logic. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray array = new JSONArray(sourceString)

    12. Unnamed JSONArray inside JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String yourJsonArray
      2. JSONArray root = new JSONArray(yourJsonArray)
      3. int rootSize = root.length()
      4. for (int i = 0, i < rootSize
      5. i++) { JSONArray inner = root. getJSONArray(i)
      6. long firstChildren = inner.getLong(0)
      7. double secondChildren = inner.getDouble(1)
      8. }

    13. Unnamed JSONArray inside JSONArray

      That's great thanks so much!. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = "[[1375056000000,23.284713745117],[1375142400000,3.809531211853],[1375228800000,9.6309003829956],[1375315200000,2.7411839962006]]"
      2. JSONArray jsonArray = new JSONArray(json)
      3. for (int i = 0
      4. i < jsonArray.length()
      5. i++){ jsonArray.getJSONArray(i).getLong(0)
      6. //do something with the key jsonArray.getJSONArray(i).getDouble(1)
      7. //do something with the value}

    14. Unnamed JSONArray inside JSONArray

      Finally use getDouble(int index and getLong(int index to retrieve values from inner arrays. in your example . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray a1 = new JSONArray("[[1375056000000,23.284713745117],[1375142400000,3.809531211853]]")
      2. for (int i=0
      3. i<a1.length()
      4. i++) { JSONArray a2 = a1.getJSONArray(i)
      5. long v1 = a2.getLong(0)
      6. double v2 = a2.getDouble(1)
      7. }

      Positive Reactions
      1. That's great - thanks so much!.

    15. How to verify given string is valid JsonArray using a net.sf.json library

      How can i verify the string as valid json array. From docu Throws JSONException if the object can not be converted to a proper JSONArray. details

      Reactions - Positive 0, Negative 2, Others 0

      1. net.sf.json.JSONArray.fromObject()

      Negative Reactions
      1. You just need to handle this exception and make some decision to return null, or throw exception by your method (and handle later).
      2. You don't really need to make special check if this is valid string because you receive this information from exception.
      Other Reactions
      1. though you are right but only when i know string is valid array, what if get that string as method arguement.please see my edit.
      2. that solution is provided by @Ankur Lathi.I am looking for solution using this API rather than making decision on basis of exception.Though i think so it is the only approach left.
      3. edited.

    16. how to parse multiple json objects with no name

      From the link you posted it looks like there are newlines between objects and only between objects). If that's right I'd approach it like this This splits the data at newlines then joins it together with commas between elements and brackets around the whole thing. details

      Reactions - Positive 2, Negative 0, Others 0

      1. String[] items = dataFromWeb.split("\n")
      2. String asJSONArrayString = Arrays.toString(items)
      3. JSONArray jsonArray = new JSONArray(asJSONArrayString)

      Positive Reactions
      1. However, the best approach would be to get that Web API to return a well-formed JSON array of JSON objects.
      2. Thanks a lot this works just fine and well enough!.
      Other Reactions
      1. If you ask for JSON, it should return valid JSON, not some garbage that looks vaguely like JSON but doesn't parse.
      2. This is probably the most practical approach.
      3. @StephenC - I agree about getting the Web API to behave.

    17. Expected BEGIN_OBJECT but was BEGIN_ARRAY

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray#getJSONObject()

    18. double quote in json simple

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray ar1 = (JSONArray)JSONValue.parse(yourJSONStr)

    19. Parsing JSON Array within JSON Object

      thanks a lot. Your code is fine just replace the following line with this line . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonMainArr = mainJSON.getJSONArray("source")

    20. Parsing JSON Array within JSON Object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"))

    21. Trouble parsing through complicated json

      It looks like the key you want to use to get your weather items is data and that will be a JSONArray. You can instead create it something like Then you can iterate through that JSONArray to see the totalResults property that you are trying to query. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray weatherObservationItems = jsonObject.getJSONArray("data")

      Positive Reactions
      1. Hope it makes sense.
      Other Reactions
      1. if I do data, how do I cylce through all the results?
      2. @Mike I've updated the answer with a sample of looping through the JSONArray and getting some of the data in the results.

    22. Remove the header from a http response(socket)

      Well this is the difficulty of using low-level bare sockets you're going to get a ton of raw data and have to handle it yourself. Set You'll have to analyze the packets and headers as they're coming out to figure out how to substring it properly. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String response = sb.toString()
      2. //do some substring voodoo on responseJSONTokener tokener = new JSONTokener(response)
      3. JSONArray jArray = new JSONArray(tokener)

      Other Reactions
      1. It is a blank line.
      2. In other words you don't know the HTTP header delimiter.

    23. JSONArray cannot be converted to JSONObject given a string

      Every tutorial i've read inserts a String and yet when I do it it errors out. Try Instead of JSON example in your question is actually a JSON array. details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONArray jsonArray = new JSONArray(new String(blah))

      Positive Reactions
      1. Excellent thank you.
      2. Just so anyone who finds this, once the JSON data was formatted correctly, it seemed to work perfectly here is the new output{"Categories":[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Ele ctrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id ":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"R emodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]}.
      Other Reactions
      1. I updated my code to your suggestion and now receive the following in logcat:05-12 03:09:22.185: E/Http Error(21193): Error in http connection org.json.JSONException: Value Categories at 0 of type java.lang.String cannot be converted to JSONObject.
      2. I'll updated the code in the morning and let everyone know how it goes.

    24. can not parse json array from php

      The key ends with a space. try EDIT:It would be better to lose the space in your php script. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray usernames = json.getJSONArray("usernames ")

    25. Creating JSON in java using org.json

      instead of using accumulate use put this way it won;t add it to a pre existing or create and add JSONArray but add it as a key to the JSONObject like this and now it'll print "test":[] . That is because in the accumulate method This is as per the API which clearly says for the accumulate method Accumulate values under a key. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object object = this.opt(key)
      2. //gets the key value. Null in your case.if (object == null) { this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value)
      3. }

    26. JSON array is not being created from a stream

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSonArray(stream)

    27. Passing String array to PHP as POST

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray devices = new JSONArray()
      2. devices.put(device1)
      3. devices.put(device2)
      4. devices.put(device3)
      5. String json = devices.toString()
      6. nameValuePairs.add(new BasicNameValuePair("devices", devices))

    28. Parsing a JSON Array from HTTP Response in Java

      Instead you should read the data from the BufferedReader as follows Then you should parse the content to get the JSON array. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. Object obj=JSONValue.parse(content.toString())
      2. JSONArray finalResult=(JSONArray)obj
      3. System.out.println(finalResult)

      Positive Reactions
      1. thanks a lot, the code works!.

    29. Mapping JSON to arrays/objects in Java - Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray topLevelArr = new JSONArray(json)
      2. JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps")

    30. How to convert HashMap to json Array in android?

      two objects for each entry whereas a list only has a single object for each entry. What you can do is to extract all Map.Entry<K,V> and then put them in the array Alternatively sometimes it is useful to extract the keys or the values to a collection or Note If you choose to use the keys as entries the order is not guaranteed the method returns a Set). details

      Reactions - Positive 0, Negative 0, Others 0

      1. Set<String> keys = map.keySet()
      2. JSONArray mJSONArray = new JSONArray(keys)

    31. How to convert HashMap to json Array in android?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray array=new JSONArray(obj.toString())

    32. How to convert HashMap to json Array in android?

      That is because the Map interface does not specify any order unless the Map happens to be a SortedMap). You can use . details

      Reactions - Positive 1, Negative 2, Others 0

      1. JSONArray jarray = JSONArray.fromObject(map )

      Positive Reactions
      1. @Forhad: Thanks, But my hash created dynamically in my code so its not suitable for me is any other option to create array with key=>value and convert in json in android activity?
      Negative Reactions
      1. You can find this library here: URL_http://json-lib.sourceforge.net/ .
      2. Thanks for your reply but still not working.
      Other Reactions
      1. :(.
      2. try this : URL_http://stackoverflow.com/questions/9210273/how-to-create-a-complex - json-using-hashmap-in-android.
      3. These classes are available in JSON-Lib library.

    33. Receiving multiple JSON objects(arrays) in java(Eclipse)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray array = json.getJSONArray ("elements")
      2. for (int counter = 0
      3. counter < array.length ()
      4. counter ++) Log.d ("element", array.getInt (counter))

    34. To read the json as a string object in android

      thats not the proper way to do check API you need to read into JSONArray and then can read specific value from JSONArray into JSONObject. Use this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray Array = statusObject.getJSONArray("speciality")
      2. for (int j = 0
      3. j < Array.length()
      4. j++) { if (Array.getJSONObject(j).has("id")) { String str1 = (Array.getJSONObject(j).getString("id"))
      5. String str2 = (Array.getJSONObject(j).getString("d_name"))
      6. .....}}

    35. Parse json array android

      BozidarPrcovski see my answer and make changes in your current code. you will need to make two changes in your current code according to string u have posted here for parsing as Json First change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObjectFor example Second change your code as for getting value from JsonArray . details

      Reactions - Positive 2, Negative 2, Others 0

      1. public JSONArray getJSONfromURL(String url){ String str_response="response from server"
      2. // convert response to JSONArray JSONArray json_Array=new JSONArray(str_response)
      3. return json_Array
      4. //<< retun jsonArray}

      Positive Reactions
      1. Yes this is the solution, THANKS ALLOT!.
      2. @BozidarPrcovski : most welcome friend :).
      Negative Reactions
      1. it gives me this in logcat01-28 13:03:57.329: E/log_tag(1708): Error in http connection java.lang.IllegalStateException: Target host must not be null, or set in parameters.
      2. scheme=null, host=null, path=www.zasvadba.mk/test.php01-28 13:03:57.379: E/log_tag(1708): Error converting result java.lang.NullPointerException: lock null01-28 13:03:57.379: E/log_tag(1708): Error parsing data org.json.JSONException: End of input at character 0 of 01-28 13:03:57.379: E/log_tag(1708): Error getJSONfromURL java.lang.NullPointerException.
      Other Reactions
      1. @BozidarPrcovski : check your URl which you are passing in getJSONfromURL is as getJSONfromURL(" URL_http://www.zasvadba.mk/test.php ").

    36. Modify json with GSON without using a POJO

      You can always get a different type than JsonElement or use JsonElement.getAsJsonObject to cast to an Object if possible). I was wrong earlier there seems to be no JsonArray adapter you'll have to get a JsonElement and use the casting tool. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jsonString = "[{\"key1\":\"Hello\",\"key2\":\"World\"}, ...]"
      2. JsonArray jsonArray = gson.fromJson(jsonString, JsonElement.class).getAsJsonArray()
      3. JsonObject firstObject = jsonArray.get(i).getAsJsonObject()
      4. firstObject.addProperty("key1", "Test")

    37. JSON encoding data for Android app

      I'm sure some php guru could help if you want to fix it on the php side. Edit is asking for an array. details

      Reactions - Positive 3, Negative 1, Others 0

      1. JSONArray JSONarr=JSONobj.getJSONArray("sample")

      Positive Reactions
      1. Glad you got it working, and thanks for updating with the working solution.
      2. You know... for kids!
      3. almost worked like that - see last edit of OP.
      Negative Reactions
      1. As an aside, I recommend using a JSON mapping library like Jackson if you are going to be doing more than very trivial work with JSON.

    38. I would like to see an example web method that passes an array of objects from aspx webservice

      and get a sub object by using the same getJSONObject method as we have used above Step 4 Now this sub sub-object contains 1 array namely sub1. So we can get this JSON array by usinggetJSONArray method Now we just need to process this array same as simple string array . details

      Reactions - Positive 3, Negative 0, Others 0

      1. JSONArray subArray = subObject.getJSONArray("sub1")

      Positive Reactions
      1. wow!
      2. Thanks a lot.
      3. superb.
      Other Reactions
      1. Let me try this and get back to you..

    39. Json parsing in array java

      The key must stand in as well e.g. A":"text You can get the C Array by using On the array you can iterate . details

      Reactions - Positive 2, Negative 2, Others 0

      1. JSONArray jsonArray = logJson.getJSONArray("C")

      Positive Reactions
      1. Thanks..
      2. with your above code I can get the value of C, but how do I get the values of D, E , F , G ??
      Negative Reactions
      1. If its an object obj.getJSONObject("D"); if its an array obj.getJSONArray("D"); The structure of this json string is pretty awkward, so it's very inconvenient to access all JSON objects.
      2. Ok, I doublechecked, according to the json specification its invalid, according to different implementations (eg.g javascript) it "might" be valid.
      Other Reactions
      1. ?
      2. Not necessarily...
      3. But I mean the key can be without ".
      4. The same way as before...

    40. Can't Convert to JSONArray for showing in ListView

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray notes = jSon.getJSONArray("notes")
      2. `

    41. Create a JSONArray

      Why dont you use Gson library its very easy to convert any object into json array json object Download Gson library then use like if Object is of List object it will create json array Gson gson new Gson() for single object . You can do it like Or create a JSONArray object and use the put method(s to add any Strings you want. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String[] data = {"stringone", "stringtwo"}
      2. JSONArray json = new JSONArray(Arrays.asList(data))

    42. Create a JSONArray

      Creating time For example Retrieving time you can fetch the value of String or JSONObject or any by their key name. For example . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray myArray = objJson.getJSONArray("array")

    43. Parsing JSON from HTTPResponse

      One or the other NOT both. Changing the JSON data As simple as adding a at the beginning and at the end Changing the Java The final Java would look a little something like Again one or the other NOT both. details

      Reactions - Positive 0, Negative 2, Others 0

      1. // OLD CODE//JSONArray jsonArray = new JSONArray(builder.toString())
      2. //for (int i = 0
      3. i < jsonArray.length()
      4. i++) {// JSONObject jsonObject = jsonArray.getJSONObject(i)
      5. //}// END OLD CODEJSONObject jsonObject = new JSONObject(builder.toString())

      Negative Reactions
      1. +1 for outlining expectations causing the error.
      2. Based on what you stated in the question, no one solution is better than the other... but if there were other factors - for example, if you were consuming 3rd party JSON and couldn't change the JSON data - then there might be a right choice and a wrong choice.
      Other Reactions
      1. JSONObject one I choose.
      2. @TechGeeky - Out of curiosity, which of the two solutions did you use?
      3. Did I made the right choice?
      4. It really depends on what you needed.

    44. JSON file with a lot of elements, how to read and print using java?

      So while browsing through the elements you should cast the value of features element to JSONArray and then iterate through the list of elements in that array. HTH. details

      Reactions - Positive 6, Negative 4, Others 0

      1. JSONArray features = (JSONArray) jsonObject.get("features")
      2. int size = features.size()
      3. for (int i = 0
      4. i < size
      5. i++){ System.out.println(features.get(i))
      6. }

      Positive Reactions
      1. I thank you for your help!
      2. I cant really converse well in programming language, especially JSON.
      3. Sure Sir!
      4. I will read up and check!
      5. something like size() etc.,?
      6. Hope you got this.
      Negative Reactions
      1. ): My bad..
      2. Sorry!.
      3. Hi @Vikdor, I got this error: The method length() is undefined for the type JSONArray.
      4. size() works, but the print out is abit weird.
      Other Reactions
      1. So, enclose those two maps in an array.
      2. I was referring to JSONArray from URL_http://www.json.org/java/index.html .
      3. Can you check the equivalent of length() method for the JSONArray in your library?
      4. json.simple's JSONArray has size() method to get the length of the array.
      5. What JSON parser library are you using?
      6. I am using json.simple library.. is that the library name you are looking for?
      7. Then, upon parsing, the JSONObject returned will be of type JSONArray and each element in that array is a JSONObject.
      8. OKay.
      9. Your entire JSON document should be a valid JSON object, i.e.
      10. either a JSONObject (map) which means everthing should be within { } or a JSONArray (array) within [].
      11. Just now i only show you 1 element, now there is 2 elements..
      12. I have modified my .json file.
      13. Updated the code snippet in my answer accordingly.

    45. Parsing JSON string in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray geoObject = jObject.getJSONArray("geodata")

    46. REST and JSON - converting string to JSON array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonArray jArray = new JsonArray()

    47. How to parse a JSONArray of JSONObjects in JAVA?

      I wonder what version of json-lib Android uses. You should use if you can. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray finalResult = new JSONArray(tokener)

    48. Android, Parsing JSON object

      Thanks . Your error is here id is itself a complex object not an array. details

      Reactions - Positive 4, Negative 1, Others 0

      1. JSONArray contestantObjects = jObject.getJSONArray("id")

      Positive Reactions
      1. Thanks Chin i could parse it.
      2. This part, i would strongly recommend that you look into a good JSON library, GSON from Google seems to be a good one.
      3. Welcome Hesam :).
      4. Wow, the tool is amazing thank you for sharing with us :).
      Negative Reactions
      1. Thanks dear Chin, based on what you mentioned i found that "id" is wrong key because i don't need its items.
      Other Reactions
      1. Based of what, should i have to parse "response" string?
      2. Here is a short tutorial: URL_http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/ .
      3. How to get body, publishedDate, refKey and title?
      4. To get publishedDate, refKey, and title, you would only need JSONObject jObject new JSONObject(response); String publishedDate jObject.get("publishedDate"); and so on.

    49. Java: Parsing more than one Json Object in a string

      So some possibilities 1. Form the string into a JSONArray and parse that Then iterate through each child of the array to get the lat/long. details

      Reactions - Positive 5, Negative 3, Others 0

      1. JSONArray jsonObj = new JSONArray("["+jsonStr.replaceAll("}{","},{")+"]")

      Positive Reactions
      1. Thanks for your help.
      2. Excellent, that's great to hear!
      3. Good luck with your project.
      4. I see you've edited your original question with PHP code - it would definitely be the right approach to fix it there!.
      5. Thanks again.
      Negative Reactions
      1. Not really sure what's wrong with it :-( .
      2. With your latest update in Eclipse its saying:Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ ).
      3. I tried the second one, and the first and I get this line upon debugging'05-03 14:45:10.452: E/AndroidRuntime(476): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX near index 1: }{'.
      Other Reactions
      1. Bugger, I didn't think the { and } needed to be escaped, so was surprised by your original comment.
      2. I have edited my answer.
      3. After fixing the php syntax it echoed the jSon string in the proper format.
      4. Apologies, you'll need to escape the characters by doing this... replaceAll("\}\{","}}{{").
      5. I've edited my answer to include PHP changes that should make it JSON-proper.
      6. All I have to do is put the objects into a JsonArray now.

    50. Java: Parsing more than one Json Object in a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. new JSONArray(serverResult)

    51. Parsing JSON and save them on SQLite Database

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray footages = location.getJSONArray("footages")

    52. Parsing JSON and save them on SQLite Database

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonArray = new JSONArray(String json)

    53. Android Twitter String to Json Array

      You are trying to parse the response as JSONObject ) while it is a JSONArray ). You should probably remove the line instead you need . details

      Reactions - Positive 0, Negative 1, Others 0

      1. JSONArray jArray = new JSONArray(json)

      Negative Reactions
      1. my mistake, see my fix.
      Other Reactions
      1. ok I've edited it and now just getting the red cross it doesn't like json.getString String json reader.readLine(); Log.v(json,"jsonfeed"); List items new ArrayList(); for (int i=0; i < json.length(); i++) { items.add(json.getString("text")); Log.i("items", "items"); } setListAdapter ( new ArrayAdapter(this, R.layout.single_item, items));.
      2. ok figured it out turns out you was right but i also needed to convert into a JSONArray JSONArray jArray new JSONArray(json);.

    54. Importing JSON into an Eclipse project

      It still doesn't work for me but at least I don't get the JSON library error anymore. Copy json-1.5.jar into the main folder from here link not into the library one and then replace every import with like you pointed out. details

      Reactions - Positive 0, Negative 0, Others 0

      1. com.google.appengine.repackaged.org.json.JSONArray

    55. Decode JSON String in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String decodedString = java.net.URLDecoder.decode("%5B%22Name%22%2C%22Vivek%22%2C%", "UTF-8")
      2. JSONArray json = new JSONArray(decodedString)

    56. How to generate JSONArray properly from Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. jsonArray.put(new JSONArray(Arrays.asList(1999, 1)))

    57. How to generate JSONArray properly from Java?

      You don't want Strings you want nested arrays. So you have to work with nested JSONArray objects Here's the standard way Or til.Collection%29 simpler Or llection%29 even-simpler . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONArray nested1 = new JSONArray()
      2. nested1.put(1999)
      3. nested1.put(1)
      4. jsonArray.put(nested1)

      Positive Reactions
      1. This works just great!.
      2. Thanks a lot for the quick an exhaustive answer !

    58. Java JSONException while creating JSONArray

      Im trying to create a new array out of a string dont i. is trying to use a JSONObject to initialize a JSONArray. details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray jArray2 = new JSONArray(content)

      Positive Reactions
      1. Thanks a lot sir, this helped me a lot!.

    59. Getting JSONObject from JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs")

    60. Java JSONArray and Dynamic keys

      Arrays don't have keys they have elements. This should be based on a java collection type use a loop structure to test it If the emailArray is empty nothing will be output if it has elements in it the value will be output. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray emailArray = contactArray.getJSONObject(i).getJSONArray("email")
      2. for(Object o: emailArray){ System.out.println(o)
      3. }

    61. Update City Spinner with notifyDataSetChanged after state is selected

      try to declare all the variable before onCreate() remove final as much possible as you can then tell me the update. Declare the city_array variable at the place where you assign a . details

      Reactions - Positive 0, Negative 1, Others 0

      1. new JSONArray()

      Negative Reactions
      1. That is how I was originally doing that see my post from a few weeks ago: URL_http://stackoverflow.com/questions/7213115/populate-city-spinner-after-state - spinner-has-been-selected/7213350#7213350 but then I get an error at new ArrayAdapter (this,android.R.layout.simple_spinner_item, city_values);.

    62. JSON Java check element is a JSONArray or JSONObject

      Yes this is because the will try to convert that String to a JSONObject what which will throw a JSONException. You should do the following Check if that object is a JSONObject by using which will return a JSONObject or null if the category object is not a json object.Then you do the following which will return your JSONArray or null if it is not a valid JSONArray . details

      Reactions - Positive 5, Negative 0, Others 0

      1. JSONArray categories
      2. if(category == null) categories=jsonObject.optJSONArray("Category")

      Positive Reactions
      1. Great Ovidiu.
      2. Superb Man.. +1..:).
      3. You're welcome!.
      4. OK No prob thanks.
      5. Thanks.
      Other Reactions
      1. none that I can think of...

    63. Android,trying to parse json data for android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jArray = new JSONArray(result)

    64. Parsing JSON Array within JSON Object

      returns a JSONArray hence you can remove the new JSONArray. The JSONArray contructor with an object parameter expects it to be a Collection or Array not JSONArray Try this . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JSONArray jsonMainArr = mainJSON.getJSONArray("source")

      Positive Reactions
      1. Hey, it worked.
      2. thanks a lot.

    65. Convert normal Java Array or ArrayList to Json Array in android

      Something along those lines should work. Beware that code is written offhand so consider it pseudo-code. details

      Reactions - Positive 1, Negative 0, Others 0

      1. String mStringArray[] = { "String1", "String2" }
      2. JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray))

      Positive Reactions
      1. Even tough JSONArray has no constructor with String[] as parameter the following code works fine for me:String[] strings {"a", "b"};JSONArray json new JSONArray(strings);System.out.println(json.toString());.
      Other Reactions
      1. Is arrays.asList necessary?

    66. JSONException on trying to create JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray array = responseObject.getJSONArray("results")
      2. for (int i = 0
      3. i < array.length()
      4. i++) {// CREATE YOUR OBJECTS}

    67. How to read stringified JSON string in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "['NPD STATION SDN BHD', 1, 2.0, true]"
      2. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str )

    68. Parse JSON object with string and value only

      simple but very efficient thank you. My pseudocode example will be as follows . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]"
      2. JSON newJson = new JSON()
      3. for (each json in jsonArray) { String id = json.get("id")
      4. String name = json.get("name")
      5. newJson.put(id, name)
      6. }return newJson

      Other Reactions
      1. Why the downvote?
      2. Can't you see I said pseudocode**?

    69. put method in the json object adds value to the first of the jsonobject;

      In other words properties of an object are accessed by name not by position and the default serialized form does not guarantee any specific order. Strict positioning comes only with arrays The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key produce the JSON string manually in what ever order necessary. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray json = new JSONArray()
      2. json.put("1")
      3. json.put("2")
      4. json.put("3")
      5. json.toString()
      6. // results in ["1", "2", "3"]

    70. Convert Java String to Json

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. new JSONArray(yourvector)

    71. Parsing JSON, not sure on how and when to use iterators (Android Platform)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray artistsArr = myObject.getJSONArray("files_informations")
      2. for (int i = 0
      3. i < artistsArr.size()
      4. i++) { // first case Log.d(TAG, artistsArr.get(i).getString("value"))
      5. // Second case Log.d(TAG, artistsArr.getString(i))
      6. }

    72. Decoding JSON format in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. someArray[] array = [ [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]], [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,3450]], [[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,34534]]] JSONArray superMasterArray = new JSONArray(array)
      2. if(superMasterArray != null){ for(int i = 0
      3. i < superMasterArray.length()
      4. i++ ){ JSONArray masterArray = (JSONArray) superMasterArray.get(i)
      5. for(int j = 0
      6. j< masterArray.length()
      7. j++){ JSONArray innerArray = (JSONArray) masterArray.get(j)
      8. innerArray.getint(0)
      9. // gives 1st element of the inner array that is 1234 innerArray.getint(1)
      10. // gives 245 innerArray.getint(2)
      11. // gives 10// if you dont know how many element in the given array, then loop it with size of array } } }

    73. JSON Array iteration in Android/Java

      make a Map 2. make a JSONArray of names . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray names= json.names()
      2. JSONArray values = json.toJSONArray(names)
      3. for(int i = 0
      4. i < values.length()
      5. i++){ if(names.getString(i).equals("description")){ setDescription(values.getString(i))
      6. } else if(names.getString(i).equals("expiryDate")){ String dateString = values.getString(i)
      7. setExpiryDate(stringToDateHelper(dateString))
      8. } else if(names.getString(i).equals("id")){ setId(values.getLong(i))
      9. } else if(names.getString(i).equals("offerCode")){ setOfferCode(values.getString(i))
      10. } else if(names.getString(i).equals("startDate")){ String dateString = values.getString(i)
      11. setStartDate(stringToDateHelper(dateString))
      12. } else if(names.getString(i).equals("title")){ setTitle(values.getString(i))
      13. } }

    74. JSON Array iteration in Android/Java

      make a JSONArray of names . This article helped me when I got started with JSON and Android On Arrays look for . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONArray menuitemArray = popupObject.getJSONArray("menuitem")

      Positive Reactions
      1. +1 nice example Paul.

    75. Convert Json Array to normal Java Array

      Wouldn't your for-loop crash then. If you don't already have a JSONArray object call Then simply loop through that building your own array. details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONArray jsonArray = new JSONArray(jsonArrayString)

      Positive Reactions
      1. thank you, it's helped.. :D.
      Negative Reactions
      1. Sorry, you're right - I'm confusing Lists with JSONArrays :) It is indeed JSONArray.length().
      Other Reactions
      1. .size() should be .length().

    76. Convert JSON structure

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. var inputString = "[ [\"task1\", 10, 99], [\"task2\", 10, 99], [\"task3\", 10, 99], [\"task1\", 11, 99], [\"task2\", 11, 99], [\"task3\", 11, 99]]"
      2. var obj = JSON.parse(inputString)
      3. var output = new Object()
      4. for (var i in obj) { var item = obj[i]
      5. var title = item[0]
      6. var first = item[1]
      7. var second = item[2]
      8. var dest = output[title]
      9. if (dest == null) { dest = { "label" : title, "data": new Array() }
      10. output[title] = dest
      11. } dest.data.push([first, second])
      12. }var outputArray = new Array()
      13. for (var t in output) { outputArray.push(output[t])
      14. }

    77. Accessing members of items in a JSONArray with Java

      By looking at your code I sense you are using JSONLIB. If that was the case look at the following snippet to convert json array to java array . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input )
      2. JsonConfig jsonConfig = new JsonConfig()
      3. jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY )
      4. jsonConfig.setRootClass( Integer.TYPE )
      5. int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig )

    78. Accessing members of items in a JSONArray with Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray.getJSONObject(int)

    79. Accessing members of items in a JSONArray with Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONArray.length()

  12. Read json from string in java

    Without Spring i need an example to consume and produce JSON. Using this you can get all the jsonarray data in variables. .. details

    1. try { String data = null
    2. String url = "localhost:8080/test/rest/Action/xyz"
    3. String[] dataArray = null
    4. DefaultHttpClient client = new DefaultHttpClient()
    5. HttpUriRequest getRequest = new HttpGet(getUrl)
    6. getRequest.addHeader("User-Agent", USER_AGENT)
    7. getRequest.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("key", "pwd"), "UTF-8", false))
    8. getRequest.setHeader("Content-Type", "application/json")
    9. HttpResponse response = client.execute(getRequest)
    10. HttpResponse response = client.execute(request)
    11. BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
    12. System.out.println("Response Code : " + response.getStatusLine().getStatusCode())
    13. data = rd.readLine()
    14. } } catch () { }try { HttpGet request = new HttpGet(url)
    15. HttpResponse response = client.execute(request)
    16. System.out.println("Response Code : " + response.getStatusLine().getStatusCode())
    17. data = EntityUtils.toString(response.getEntity())
    18. dataArray = data.split(",")
    19. } catch (Exception ex) { } JSONObject mJSONObject = new JSONObject(data)
    20. try { JSONArray mjSONArray = mJSONObject.getJSONArray("values")
    21. for (int i = 0
    22. i < mjSONArray.length()
    23. i++) { JSONObject obj
    24. obj = mjSONArray.getJSONObject(i)
    25. valu = obj.getString("valu")
    26. valu1= obj.getString("valu1")
    27. valu2= obj.getString("valu2")
    28. system.out.println(valu)
    29. system.out.println(valu1)
    30. system.out.println(valu2)
    31. }

    Positive Reactions
    1. i am able to print it but how to save individual data into a variable and use it further.
    2. check my update you can get all value in your values array.
    3. json array and each value in that array.
    4. json array or single json value?
    Negative Reactions
    1. still same error.
    Other Reactions
    1. getting the below exceptionA JSONObject text must begin with '{' at 1 [character 2 line 1].
    2. if the above json is from url can i read it without saving it to string.
    3. i am able to do system out as string but unable to read it.
    4. try my whole code in main method.. i have updated answer.
    5. what do u want in variable?
    6. not working?
    7. make sure you have data in jsonobject?
    8. public class olaptemplate {public static void main(String[] args) {try {URL url new URL(" URL_http://localhost:8080/test/rest/Action/xyz ");httpURLConnection conn (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");c onn.setRequestProperty("Accept", "application/json");BufferedReader br new BufferedReader(new InputStreamReader(conn.getInputStream())));String output;StringBuilder sb new StringBuilder();while ((output br.readLine()) != null) {sb.append(output);System.out.println("Data,."
    9. don't use URL.. store url in string format then get response in String data..
    10. + output);}conn.disconnect(); } catch (){ }}}.
    11. here my url has json data.
    12. why?
    13. then what do u mean by read?

  13. Json Format error, ask for array when he already gets one

    My following method is suggested to take a json object with an array associated with. . .. details

    1. Gson gson = new Gson()
    2. String jsonOutput = "{ \"array\": [{ \"id\" : \"3\", \"name\" : \"hello_world\" }, { \"id\" : \"2\", \"name\" : \"hello_world\" }] }"
    3. JsonObject root = new JsonParser().parse(jsonOutput).getAsJsonObject()
    4. JsonArray terms = root.getAsJsonArray("array")
    5. //JSONArray cms = jsonObject.getJSONArray("array")
    6. MyModel[] arr = gson.fromJson(terms.toString(), MyModel[].class)

    Positive Reactions
    1. Without that issue his code would work perfectly as-is.
    2. His JSON is perfectly fine in terms of structure, it's an array of his Category objects.
    Negative Reactions
    1. His issue is the products field inside those is being returned inconsistently by the server as either an object or an array.

    • See Also (4)
    1. how to read values from jsonarray?

      This is an approach. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonElement jsonElement = new JsonParser().parse(new FileReader("D:/jdemo.json"))
      2. JsonObject jsonObject = jsonElement.getAsJsonObject()
      3. JsonArray jsonArray = jsonObject.getAsJsonArray("body_stats")
      4. for(JsonElement body_stats : jsonArray) { JsonElement girths = body_stats.getAsJsonObject().get("girths")
      5. if(griths !=null) { //The logic } }

    2. JSON parsing using Gson for java

      Json can be parsed like this Here is an example http-get-solr-request-and.html url-encode-http-get-solr-request-and.html . A simple example to parse a JSON like this some_array "some_element\":1,\"some_more_element\":2 some_other_element 3 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser parser = new JsonParser()
      2. JsonObject jo = (JsonObject) parser.parse(data)
      3. JsonElement je = o.get("some_array")
      4. //Parsing back the string as Array JsonArray ja = (JsonArray) parser.parse(o.get("some_array").getAsString())
      5. for (JsonElement jo : ja) { JsonObject j = (JsonObject) jo
      6. // Your Code, Access json elements as j.get("some_element") }

    3. How to retrieve JSON data inside an JSON object?

      You are getting time and track properties of Leg object not the Origin object. It should be . details

      Reactions - Positive 1, Negative 1, Others 0

      1. JSONParser parser = new JSONParser()
      2. Object obj = parser.parse(Planner.getPlanner().getJsonDataForTrip(Planner.getPlanner().getStartLocationID(), Planner.getPlanner().getDestinationID()))
      3. JSONObject topObject = (JSONObject) obj
      4. JSONObject locationList = (JSONObject) topObject.get("TripList")
      5. JSONArray array = (JSONArray) locationList.get("Trip")
      6. Iterator<JSONObject> iterator = array.iterator()
      7. while (iterator.hasNext()) { JSONObject jsonObj = iterator.next()
      8. jsonObj = (JSONObject) jsonObj.get("Leg")
      9. String line = (String) jsonObj.get("name")
      10. Planner.getPlanner().setLines(line)
      11. System.out.println(jsonObj.get("Origin"))
      12. // Added this line jsonObj = (JSONObject) jsonObj.get("Origin")
      13. String time = (String) jsonObj.get("time")
      14. String track =(String) jsonObj.get("track")
      15. System.out.println(line)
      16. System.out.println(time)
      17. System.out.println(track)
      18. }

      Positive Reactions
      1. Yeh, its working now but with a smaller expection.
      Negative Reactions
      1. Oh, I've overlooked the time format.
      Other Reactions
      1. I've fixed the code.

    4. How to get JSON data from an url in Java?

      Practice makes perfect. You could try JSON Simple simple/ Example Just be careful to check for nulls/be careful with casting and such. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONParser jsonParser = new JSONParser()
      2. JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString)
      3. for (int i = 0
      4. i < jsonArray.size()
      5. i++) { JSONObject obj = (JSONObject) jsonArray.get(i)
      6. //Access data with obj.get("item_name")}

  14. Convenient way to extract data from the MtGox/PubNub JSON API?

    None .. details

    1. import com.pubnub.mtgox.MtGox
    2. import com.pubnub.mtgox.MtGoxCallback
    3. import org.json.JSONObject
    4. public class PubnubMtGoxSample {
    5. public static void main(String[] args) {
    6. MtGox mtgx = new MtGox()
    7. mtgx.subscribe(
    8. "ticker.BTCUSD",
    9. new MtGoxCallback() {
    10. @Override
    11. public void callback(JSONObject data) {
    12. try {
    13. String channel_name = data.getString("channel_name")
    14. String avg_value =
    15. data.getJSONObject("ticker").getJSONObject("avg").getString("value")
    16. System.out.println(channel_name + " : " + avg_value)
    17. } catch (Exception e) {
    18. }
    19. }
    20. })
    21. }
    22. }

    • See Also (1)
    1. Are there ready made Java classes for the MtGox/PubNub JSON API?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.pubnub.mtgox.MtGox
      2. import com.pubnub.mtgox.MtGoxCallback
      3. import org.json.JSONObject
      4. public class PubnubMtGoxSample {
      5. public static void main(String[] args) {
      6. MtGox mtgx = new MtGox()
      7. mtgx.subscribe(
      8. "ticker.BTCUSD",
      9. new MtGoxCallback() {
      10. @Override
      11. public void callback(JSONObject data) {
      12. try {
      13. String channel_name = data.getString("channel_name")
      14. String avg_value =
      15. data.getJSONObject("ticker").getJSONObject("avg").getString("value")
      16. System.out.println(channel_name + " : " + avg_value)
      17. } catch (Exception e) {
      18. }
      19. }
      20. })
      21. }
      22. }

  15. Adding an existing json string with Gson

    None .. details

    1. JsonParser parser = new JsonParser()
    2. JsonObject obj = parser.parse(jsonStr).getAsJsonObject()
    3. obj.get("version")
    4. // Version field

    • See Also (8)
    1. How to convert String to JSONObject in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String Data=response.getEntity().getText().toString()
      2. // reading the string value JSONObject json = (JSONObject) new JSONParser().parse(Data)
      3. String x=(String) json.get("phonetype")
      4. System.out.println("Check Data"+x)
      5. String y=(String) json.get("cat")
      6. System.out.println("Check Data"+y)

    2. parsing JSON output using google's gson in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonObject rootObject = new JsonParser().parse(json).getAsJsonObject()
      2. JsonObject carObject = rootObject.getAsJsonObject("Car")
      3. String carName = carObject.get("name").getAsString()

    3. deserialize JSON data for different types of objects

      Maybe a example or tutorial. I would parse it as a general JsonObject using then find something unique about each json schema and then depending on which schema convert it to a bean using . details

      Reactions - Positive 0, Negative 1, Others 0

      1. JsonParser parser = new JsonParser()
      2. JsonObject jsonObject = parser.parse(json).getAsJsonObject()

      Negative Reactions
      1. Im going to go with this approach, although its not as sophisticated as I was hoping.

    4. How to convert json objects with number as field key in Java?

      Because this json object uses int as the field key that you cannot specify the field key name when deserialize it. Thus I need to extract the value set from the set first Now set contains a set of in my case is 1,{id:1,value:something. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser parser = new JsonParser()
      2. JsonObject obj = parser.parse(json).getAsJsonObject()
      3. Set<Entry<String,JsonElement>> set = obj.entrySet()

    5. Parse the JSON in spring?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser parser = new JsonParser()
      2. JsonElement element = parser.parse(yourJsonString)
      3. JsonObject jsonObject = element.getAsJsonObject()

    6. GSON mapping null value for POJO properties

      . use not response but response.job not use this may help . details

      Reactions - Positive 2, Negative 2, Others 0

      1. String a = "{\"response\": {\"job\":{\"eta\":-1,\"status\":\"approved\",\"mt\":1,\"lc_tgt\":\"fr\",\"body_src\":\"Please translated me.\",\"body_tgt\":\"S'il vous plat traduire moi.\",\"unit_count\":3,\"tier\":\"machine\",\"credits\":0,\"ctime\":\"2013-02-07 14:56:12.391963\",\"lc_src\":\"en\",\"slug\":\"0\",\"job_id\":\"NULL\"}},\"opstat\":\"ok\"}"
      2. Job j = I.gson().fromJson( ((JsonObject) ((JsonObject) new JsonParser().parse(a)).get("response")).get("job"), Job.class)
      3. System.out.println(j.getEta())

      Positive Reactions
      1. Thanks @Ferhat (+1) - however that doesn't change anything.
      2. alex answered :) but still u have to response.job field in order to convert to POJO.
      Negative Reactions
      1. Come to think of it, how does GSON know that body_src should map to sourceLanguage?
      2. I think that's the root of the problem here.
      Other Reactions
      1. You can use annotation to clarify it, look at my comment.
      2. i edited my response.
      3. my code for it.
      4. Still getting null.
      5. this may help.
      6. ok 'response' doesnot map any object.
      7. 'a' is your 'response' object.

    7. Name/value pair loop of JSON Object with Java & JSNI

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. json_string = "{'data':{'key':'test','key2':'test3','key3':'test3'}}"JSONObject json_data = JSONParser.parseLenient(json_string)
      2. JSONObject data = json_data.get("data").isObject()
      3. Set<String> keys = data.keySet()
      4. for (String key : keys) { String value = data.get(key).isString().stringValue()
      5. }

    8. Reading JSon String with Gson

      But a link in the post that you pointed me to lead me to come up with this which works for me. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JsonParser parse = new JsonParser()
      2. JsonObject jobj = (JsonObject)parse.parse(status)
      3. Set<Map.Entry<String, JsonElement>> map = jobj.entrySet()
      4. Iterator<Map.Entry<String, JsonElement>> iterator = map.iterator()
      5. int size = map.size()
      6. for( int k = 0
      7. k < size
      8. k++ ){ Map.Entry<String, JsonElement> entry = iterator.next()
      9. String key = entry .getKey()
      10. JsonObject jele = (JsonObject)entry.getValue()
      11. }

      Positive Reactions
      1. And breaking things out like that, while it is more code.
      2. It's easier for them when they look at it.
      Other Reactions
      1. Most JSON libraries have one or two line operations to do the same; there should not be any need to manually write this code.
      2. With Gson I think you would need to pass TypeToken> to get intended result.
      3. While I understand that, I normally have people who work with my that while they can do some programing it's not there job.

  16. Unchecked conversion

    If you just want to remove the warning The expression of type Iterator needs unchecked conversion to conform to Iterator then do this but this result in new warning but your old warning is removed. Type safety Unchecked cast from Iterator to Iterator<String For removing all your warnings . .. details

    1. Iterator<?> it = schemaJSON.getJSONObject("body").keys()
    2. while(it.hasNext()){ String nextElement = (String) it.next()

    Positive Reactions
    1. @Nfear please accept the answer as proposed by Ben in URL_http://stackoverflow.com/questions/20378562/unchecked - conversion/20378705#20378705 he was first to point to solution....
    Other Reactions
    1. Your last edit seems to have solved this :).

    • See Also (4)
    1. Unchecked conversion

      You were first to solve the problem. If you just want to remove the warning The expression of type Iterator needs unchecked conversion to conform to Iterator then do this but this result in new warning but your old warning is removed. details

      Reactions - Positive 1, Negative 0, Others 0

      1. Iterator<String> it = (Iterator<String>)schemaJSON.getJSONObject("body").keys()

      Positive Reactions
      1. @Nfear please accept the answer as proposed by Ben in URL_http://stackoverflow.com/questions/20378562/unchecked - conversion/20378705#20378705 he was first to point to solution....
      Other Reactions
      1. Your last edit seems to have solved this :).

    2. JSON Array iteration in Android/Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Overridepublic Iterator iterator() { return this.myArrayList.iterator()
      2. }

    3. Json conversion

      I recommend the jackson-library it makes things very easy. To use it you would have an object like this Then you can use the objectMapper from the library to go from an array that you have in memory to a json String like so Of course doing it this way depends on how your ids are stored but for me it generally makes my code a lot cleaner and the Jackson Library is pretty good performance wise. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Ids[] idsArray = new Ids[2]
      2. //add ids object to array String jsonString = objectMapper.writeValueAsString(idsArray)

    4. Parsing array of JSON arrays in Groovy

      I think I need to convert the string into an Array first and then use JSONObject on each individual item from json.org. EDIT Groovy since 1.8.0 has an integrated JsonSlurper Old answer below Use JsonSlurper An example script to read that response would be This outputs As you can see list is a list of Maps so if you just wanted a list of the names for example you could just do To use this in your Gaelyk app you should just need to download-json lib-2.3-jdk15.jar-from-here and do something similar without the Grab then as you'll have the jar in your WEB-INF/lib folder. details

      Reactions - Positive 2, Negative 0, Others 0

      1. @Grab('net.sf.json-lib:json-lib:2.3:jdk15')import net.sf.json.groovy.JsonSlurper// Example Response Datadef restResponse = '[{"uid":10512213, "name":"Bob"},{"uid":7208201, "name":"John"},{"uid":10570, "name":"Jim"},{"uid":1799657, "name":"Sally"}]'// Parse the responsedef list = new JsonSlurper().parseText( restResponse )// Print them out to make surelist.each { println it }

      Positive Reactions
      1. Good idea!
      2. The easiest process was to run the script above which downloaded the jars into the .groovy directory.
      Other Reactions
      1. Strange you had to download Ivy though...
      2. Does @Grab work in eclipse?
      3. (I had to download ivy to get @Grab to work) I then copied the jars to the lib directory.
      4. I believe so...but it won't work on the app engine when you deploy your gaelyk app.

  17. Error Parsing JSON Data - Asynchronous Task

    But here it is:[{"KEY_ROWID "1","KEY_NAME":"Andrew","KEY_SCORE":"100","KEY_DATE":"0000-00-00 00:00:00"}, KEY_ROWID":"2","KEY_NAME":"Peter","KEY_SCORE":"5000","KEY_DATE":"2013-11-29 10:58:21" Thanks:). Form your code The problem is that it might be not Json exception but any Exception. .. details

    1. ...catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error parsing data " + e.toString())
    2. }

    Positive Reactions
    1. I will try your handler suggestion later - thanks :).
    Negative Reactions
    1. I removed the main Exception and the application crashes.

    • See Also (9)
    1. Android Java; How can I parse a local JSON file from assets folder into a ListView

      First of all read the Json File from your assests file using below code. and then you can simply read this string return by this function as For further details regarding JSON Read-HERE . details

      Reactions - Positive 5, Negative 4, Others 0

      1. JSONObject obj = new JSONObject(loadJSONFromAsset())
      2. JSONArray m_jArry = obj.getJSONArray("formules")
      3. ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>()
      4. HashMap<String, String> m_li
      5. for (int i = 0
      6. i < m_jArry.length()
      7. i++) { JSONObject jo_inside = m_jArry.getJSONObject(i)
      8. Log.d("Details-->",jo_inside.getString("formule"))
      9. String formula_value = jo_inside.getString("formule")
      10. String url_value = jo_inside.getString("url")
      11. //Add your values in your `ArrayList` as below: m_li=new HashMap<String, String>()
      12. m_li.put("formule", formula_value )
      13. m_li.put("url", url_value )
      14. formList.add(m_li)
      15. //Same way for other value... }

      Positive Reactions
      1. Just replace json_return_by_the_function with JSONObject obj new JSONObject(loadJSONFromAsset()); like this.
      2. Size seems correct.
      3. It works but when I try to log my json string that's printing not the entire file content.
      4. @Raghunandan Thanks for your suggestion.
      5. op's reading from assests folder is fine he is passing null as the context.
      Negative Reactions
      1. @GrlsHu I have a problem, when I run the app it crashes and I don't know what's the problem, Eclipse doesn't notify me any syntax error or any problem.
      2. @GrlsHu I have a problem in this line: JSONObject obj new JSONObject(json_return_by_the_function);Do I have to replace "json_return_by_the_function" with something?
      3. m_li.put("url", url); too, it should be m_li.put("url", url_value);I almost cried until I noticed this.
      4. @WildSushii Can you tell me where exactly you are getting error?
      Other Reactions
      1. also m_li.put("formula", formula); should be m_li.put("formula", formula_value); and should be using Log instead of System.out.println.
      2. @GrIsHu no need to create arraylist in for loop.
      3. I'm kinda new to Java :(.
      4. :).
      5. Try to debug your code.
      6. Do I have to surround it with a try-catch statement right?
      7. When I replaced "json_return_by_the_function" with "loadJSONFromAsset()" everything screw up and surrounding it with a try-catch solved it.
      8. I have updated my answer.
      9. Do you have an idea ?
      10. @WildSushii I already updated my answer.
      11. Yes you need to surround the JSONObject with try..catch...
      12. @GrisHu thx for your snippet.

    2. Remove duplicates from a Json String in Java?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = "{\"Sign_In_Type\":\"Action\",\"Sign_In_Type\":\"Action\"}"
      2. try { JSONObject json_obj = new JSONObjectIgnoreDuplicates(json)
      3. String type = json_obj.getString("Sign_In_Type")
      4. } catch (JSONException e) { throw new RuntimeException(e)
      5. }

    3. JSON parsing issue not resolved

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Error parsing data org.json.JSONException: End of input at character 0 of

    4. Date format retrieved from a service

      yeah i know it in java script but im new in android development and i want to change the format into java thanks for your answer. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. String mDate = getFormattedDate(e.getString("JSON OBJECT"))
      2. private String getFormattedDate(String stringDate) throws JSONException { String strDate = stringDate.replace("/Date(", "").replace(")/", "")
      3. strDate = strDate.substring(0, strDate.indexOf("+"))
      4. Long longDate = Long.parseLong(strDate, 10)
      5. Date mDate = new Date(longDate)
      6. SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy")
      7. String formattedDate = sdf.format(mDate)
      8. return formattedDate
      9. }

      Positive Reactions
      1. This is how i found a solution to format a JSON Date to a readable format, :) :) :).
      Other Reactions
      1. JSONObject e json.getJSONObject(i);.