The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Answer from user1931858 on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › stream › JsonParser.html
JsonParser (Java(TM) EE 7 Specification APIs)
The parser can generate the following ... VALUE_NULL. For example, for an empty JSON object ({ }), the parser generates the event START_OBJECT with the first call to the method next() and the event END_OBJECT with the second call to the method next()....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript - MDN Web Docs
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson jsonparser
Gson JsonParser (with Examples) - HowToDoInJava
April 4, 2023 - import com.google.gson.JsonElement; ... void main(String[] args) { String json = "{'id': 1001, " + "'firstName': 'Lokesh'," + "'lastName': 'Gupta'," + "'email': 'howtodoinjava@gmail.com'}"; JsonElement jsonElement = ...
🌐
GitHub
github.com › google › gson › blob › main › gson › src › main › java › com › google › gson › JsonParser.java
gson/gson/src/main/java/com/google/gson/JsonParser.java at main · google/gson
* <p>Here's an example of parsing from a string: * * <pre> * String json = "{\"key\": \"value\"}"; * JsonElement jsonElement = JsonParser.parseString(json); * JsonObject jsonObject = jsonElement.getAsJsonObject(); * </pre> * * <p>It can also parse from a reader: * * <pre> * try (Reader ...
Author   google
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › latest › com.google.gson › com › google › gson › JsonParser.html
JsonParser - gson 2.13.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.13.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.13.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.go...
🌐
Jenkov
jenkov.com › tutorials › java-json › gson-jsonparser.html
GSON - JsonParser
January 27, 2021 - Once you have created a JsonParser you can parse JSON into a tree structure with it. Here is an example of parsing a JSON string into a tree structure of GSON objects with the JsonParser:
Top answer
1 of 16
962

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

2 of 16
714

For the sake of the example lets assume you have a class Person with just a name.

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

Jackson (Maven)

My personal favourite and probably the most widely used.

ObjectMapper mapper = new ObjectMapper();

// De-serialize to an object
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John

// Read a single attribute
JsonNode nameNode = mapper.readTree("{\"name\": \"John\"}");
System.out.println(nameNode.get("name").asText());

Google GSON (Maven)

Gson g = new Gson();

// De-serialize to an object
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

// Read a single attribute
JsonObject jsonObject = new JsonParser().parseString("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John

Org.JSON (Maven)

This suggestion is listed here simply because it appears to be quite popular due to stackoverflow reference to it. I would not recommend using it as it is more a proof-of-concept project than an actual library.

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John
🌐
Baeldung
baeldung.com › home › json › using static methods instead of deprecated jsonparser
Using Static Methods Instead of Deprecated JsonParser | Baeldung
June 20, 2024 - @Test public void givenJsonString_whenUsingParseString_thenJsonObjectIsExpected() { JsonObject jsonObjectAlt = JsonParser.parseString(jsonString).getAsJsonObject(); assertEquals(expectedJsonObject, jsonObjectAlt); }
Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › javas-jsonparser-parse-method-explained-76b126f6110e
Java’s JsonParser.parse() Method Explained | Medium
October 13, 2024 - Learn how to use Java's JsonParser.parse() method for parsing JSON data, including examples, performance tips, and comparisons to modern alternatives.
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonparser
com.google.gson.JsonParser.parse java code examples | Tabnine
String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}"; JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject)jsonParser.parse(json); Assert.assertNotNull(jo); Assert.assertTrue(jo.get("Success").getAsString()); ...
🌐
Tabnine
tabnine.com › home page › code › java › org.json.simple.parser.jsonparser
org.json.simple.parser.JSONParser.parse java code examples | Tabnine
JSONObject data; try { JSONParser helper = new JSONParser(); data = (JSONObject)helper.parse(String); } catch (ParseException parse) { // Invalid syntax return; } // Note that these may throw several exceptions JSONObject node = (JSONObject...
🌐
JAXB
javaee.github.io › javaee-spec › javadocs › javax › json › stream › JsonParser.html
JsonParser (Java(TM) EE 8 Specification APIs)
JsonParser parses JSON using the pull parsing programming model. In this model the client code controls the thread and calls the method next() to advance the parser to the next state after processing each element. The parser can generate the following events: START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, and VALUE_NULL. For example...
🌐
Oracle
docs.oracle.com › javame › 8.0 › api › json › api › com › oracle › json › stream › JsonParser.html
JsonParser (JSON Documentation)
The methods next() and hasNext() enable iteration over parser events to process JSON data. JsonParser provides get methods to obtain the value at the current state of the parser. For example, the following code shows how to obtain the value "John" from the JSON above:
🌐
Javadoc.io
javadoc.io › doc › com.google.code.gson › gson › 2.6.2 › com › google › gson › JsonParser.html
JsonParser - gson 2.6.2 javadoc
Bookmarks · Latest version of com.google.code.gson:gson · https://javadoc.io/doc/com.google.code.gson/gson · Current version 2.6.2 · https://javadoc.io/doc/com.google.code.gson/gson/2.6.2 · package-list path (used for javadoc generation -link option) · https://javadoc.io/doc/com.goog...
🌐
Gwtproject
gwtproject.org › javadoc › latest › com › google › gwt › json › client › JSONParser.html
JSONParser (GWT Javadoc)
public class JSONParser extends Object · Parses the string representation of a JSON object into a set of JSONValue-derived objects. See Also: JSONValue · Fields · Modifier and Type · Field · Description · (package private) static final JavaScriptObject · typeMap · All MethodsStatic MethodsConcrete MethodsDeprecated Methods · Modifier and Type · Method · Description · static JSONValue · parse · (String jsonString) Deprecated. use parseStrict(String) static JSONValue ·
Top answer
1 of 5
30

If you have the JsonParser then you can use jsonParser.readValueAsTree().toString().

However, this likely requires that the JSON being parsed is indeed valid JSON.

2 of 5
6

I had a situation where I was using a custom deserializer, but I wanted the default deserializer to do most of the work, and then using the SAME json do some additional custom work. However, after the default deserializer does its work, the JsonParser object current location was beyond the json text I needed. So I had the same problem as you: how to get access to the underlying json string.

You can use JsonParser.getCurrentLocation.getSourceRef() to get access to the underlying json source. Use JsonParser.getCurrentLocation().getCharOffset() to find the current location in the json source.

Here's the solution I used:

public class WalkStepDeserializer extends StdDeserializer<WalkStep> implements
    ResolvableDeserializer {

    // constructor, logger, and ResolvableDeserializer methods not shown

    @Override
    public MyObj deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
            JsonProcessingException {
        MyObj myObj = null;

        JsonLocation startLocation = jp.getCurrentLocation();
        long charOffsetStart = startLocation.getCharOffset();

        try {
            myObj = (MyObj) defaultDeserializer.deserialize(jp, ctxt);
        } catch (UnrecognizedPropertyException e) {
            logger.info(e.getMessage());
        }

        JsonLocation endLocation = jp.getCurrentLocation();
        long charOffsetEnd = endLocation.getCharOffset();
        String jsonSubString = endLocation.getSourceRef().toString().substring((int)charOffsetStart - 1, (int)charOffsetEnd);
        logger.info(strWalkStep);

        // Special logic - use JsonLocation.getSourceRef() to get and use the entire Json
        // string for further processing

        return myObj;
    }
}

And info about using a default deserializer in a custom deserializer is at How do I call the default deserializer from a custom deserializer in Jackson

🌐
CSharpCodi
csharpcodi.com › home › search c# examples
Search C# Examples - CSharpCodi
May 5, 2022 - By voting up you can indicate which examples are most useful and appropriate. 0 · Project: corefxlab Source File: JsonParser.cs · [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ParsePropertyName() { SkipWhitespace(); ParseString(); _valuesIndex++; } 0 ·
🌐
Json Parser Online
json.parser.online.fr
Json Parser Online
Analyze your JSON string as you type with an online Javascript parser, featuring tree view and syntax highlighting. Processing is done locally: no data send to server.