Using org.json library:

try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
Answer from dogbane on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ jsonobject-tostring-how-to-convert-json-to-a-string-in-java
JSONObject.toString() โ€“ How to Convert JSON to a String in Java
April 14, 2023 - In this article, we will explore how to use JSONObject.toString() method to convert JSON objects to strings in Java. We will also discuss the benefits of using this method, and provide examples of how to use it in practical applications.
Discussions

Parsing JSON string in Java - Stack Overflow
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get the following error- Exception in thread "main" java.lang. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert a String into JSON String
Vamsi Pavan Mahesh Gunturu is having issues with: I am calling an Online API which returns data in the JSON format, Since I am HTTPUrlConnection, InputStreamReader, I get a stringbuffer which ha... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
2
September 3, 2015
How to convert json string to pojo if json response starts with [] instead of {} ??
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnjava
12
1
August 21, 2023
create a json from the toString method
A) it's not well formed, you're missing quotes for everything that's not a number, and in order to add quotes inside your string you need to escape them. B) Use GSon, Jackson or any 3rd party library, you're going to save yourself a million headaches More on reddit.com
๐ŸŒ r/javahelp
6
1
July 13, 2023
๐ŸŒ
Medium
medium.com โ€บ @bectorhimanshu โ€บ parsing-a-string-into-a-jsonobject-in-java-and-vice-versa-1589b0b9edd2
Parsing a String into a JSONObject in Java and vice-versa | by bectorhimanshu | Medium
September 29, 2023 - In this blog, I will provide examples for both converting a JSONObject to a String and parsing a String into a JSONObject using the org.json.JSONObject class. a. To create a new JSONObject with desired properties in Java, we will need to use a JSON library. In this example, weโ€™ll use the ...
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-convert-json-to-string-420796
How to convert JSON to string | LabEx
This tutorial provides comprehensive guidance on transforming JSON objects into string representations using various Java techniques and libraries, helping developers handle data serialization efficiently. JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format that is easy for humans to read and write and simple for machines to parse and generate.
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ convert java object to json
Convert Java object to JSON - Tabnine
July 25, 2024 - For example: {โ€œidโ€:1,โ€nameโ€:โ€SiAmโ€,โ€colorโ€:โ€Creamโ€,โ€eyecolorโ€:โ€Blueโ€,โ€breedโ€:โ€Siameseโ€} JSON is interoperable, meaning that itโ€™s language/platform independent.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-convert-json-string-to-json-object
Java Program to Convert JSON String to JSON Object - GeeksforGeeks
January 30, 2022 - // Java Program to demonstrate ... String jsonString; jsonString = "{"; jsonString += "gfgId : 10001,"; jsonString += "username : 'Jack jon',"; jsonString += "gender : 'M'"; jsonString += "}"; // creating object of gson ...
Find elsewhere
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ convert java objects to json with jackson
Convert Java Objects to JSON with Jackson - Mkyong.com
April 24, 2024 - ObjectMapper mapper = new ... // JSON string to Java Object String json = "{\"name\": \"mkyong\", \"age\": 20}"; Person obj = mapper.readValue(json, Person.class); This example uses Jackson to convert a Java object ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ json โ€บ json_java_example.htm
JSON with Java
Following is another example that ... Boolean(true)); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); System.out.print(jsonText); } } On compiling and executing the above program, ...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ convert string to jsonobject with gson
Convert String to JsonObject with Gson | Baeldung
May 5, 2025 - When working with JSON in Java using the Gson library, we have several options at our disposal for converting raw JSON into other classes or data structures that we can work with more easily. For example, we can convert JSON strings to a Map<String, Object> or create a custom class with mappings.
๐ŸŒ
Java67
java67.com โ€บ 2016 โ€บ 10 โ€บ 3-ways-to-convert-string-to-json-object-in-java.html
3 ways to convert String to JSON object in Java? Examples | Java67
That's all about how to convert String to JSON objects in Java. You can use any of the json-simple, Gson, or Jackson for parsing JSON messages received from web services, each of them has its own advantage and disadvantages. For example, Json-simple has a small memory footprint means it's quite suitable for J2ME and Android clients where you have memory constraint while Jackson is feature-rich JSOn library which is probably better supported for a large project and application.
Top answer
1 of 7
100

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

In addition, you must remove the two instances of extra } in your JSON data following longitude.

   private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray.

Here is the fully working and tested corrected code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}

Here's the output:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
2 of 7
6

To convert your JSON string to hashmap you can make use of this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

๐ŸŒ
IBM
ibm.com โ€บ support โ€บ pages โ€บ creating-json-string-json-object-and-json-arrays-automation-scripts
Creating a JSON String from JSON Object and JSON Arrays in Automation Scripts
# creating a JSON String (directly ... creating a JSON formatted String def createJSONstring(): obj = JSONObject() obj.put('FIELD_1', 'VALUE_1') obj.put('FIELD_2', 0) obj.put('FIELD_3', 1.1) obj.put('FIELD_4', True) # add as many fields as needed ......
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-convert-string-to-json-object-in-java
How to Convert String to JSON Object in Java - javatpoint
How to Convert String to JSON Object in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
๐ŸŒ
Oreate AI
oreateai.com โ€บ blog โ€บ javas-json-to-string-conversion-a-friendly-guide โ€บ cb834ceb54afc036f7a2bf3a7f816bd9
Java's JSON to String Conversion: A Friendly Guide - Oreate AI Blog
February 18, 2026 - But for the specific query of converting JSON to a string, the toJson() method is our star. Jackson is another heavyweight in the JSON processing world. It's often favored for its performance and flexibility, especially in more complex enterprise ...
๐ŸŒ
Dadroit
dadroit.com โ€บ json-to-string
Quick JSON to String Conversion Tool
Strings are crucial for text processing and are widely used in scenarios like data conversion, where textual content is formatted, encoded, or decoded for various applications, such as in web development, database operations, and file interactions. To convert JSON to String, visit the tool address, input your JSON data โ€”or load your JSON fileโ€” and the tool will display the corresponding String output in real time.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ working-with-json-data-in-java
Working with JSON Data in Java - GeeksforGeeks
December 23, 2025 - import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class JavaJsonDecoding { public static void main(String[] args) { String jsonString ="{\"Full Name\":\"Ritu Sharma\",\"Tuition Fees\":65400.0,\"Roll No.\":1704310046}"; ...
๐ŸŒ
Studytonight
studytonight.com โ€บ java-examples โ€บ how-to-convert-string-to-json-and-vice-versa
How to Convert String to JSON and Vice Versa - Studytonight
There are three methods to convert JSON to String and Vice Versa in Java ... While running a program where these libraries are included we need to download these jar files and add them inside the project according to IDE otherwise functions from these libraries will not support and cause an error. You can refer following links to download these libraries ... Let's look one by one with the help of examples.