I hope you were joking about writing your own parser. :-)

For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:

Map<String,Object> result =
        new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String)

Answer from StaxMan on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › convert json string to map using jackson
Convert JSON string to Map using Jackson | mkyong.com
April 23, 2024 - String json = "..."; ObjectMapper mapper = new ObjectMapper(); // convert JSON string to Map Map<String, Object> map = mapper.readValue(json, new TypeReference<>() {}); ... package com.mkyong.json.jackson; import com.fasterxml.jackson.core....
Discussions

java - Convert a JSON String to a HashMap - Stack Overflow
If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps: More on stackoverflow.com
🌐 stackoverflow.com
java - creating Hashmap from a JSON String - Stack Overflow
HashMaps are not ordered: .../docs/api/java/util/HashMap.html 2017-06-02T19:56:39.573Z+00:00 ... Save this answer. ... Show activity on this post. You can use Google's Gson library to convert json to Hashmap. Try below code · String jsonString = "Your JSON string"; HashMap map = new ... More on stackoverflow.com
🌐 stackoverflow.com
java - How to convert a JSON string to a Map<String, String> with Jackson JSON - Stack Overflow
It's not so much weird as showing that Java is more complex than we might think. 2012-10-30T22:02:35.03Z+00:00 ... Krige: I thought the hard bit was getting the mapper going, but I've added the note on how to apply the technique to a string 2013-04-15T21:53:08.893Z+00:00 ... One minor comment: the first line of creating JsonFactory ... More on stackoverflow.com
🌐 stackoverflow.com
String with JSON inside to HashMap (instead to objects)
Your JSON is not an object but an array. You'll have to deserialise it to a list of Maps, not a Map. More on reddit.com
🌐 r/javahelp
6
1
March 17, 2020
🌐
Stack Abuse
stackabuse.com › convert-json-string-to-java-map-with-jackson
Convert JSON String to Java Map with Jackson
March 16, 2023 - Map<String, TASK_STATUS> result = objectMapper.readValue(json, new TypeReference<LinkedHashMap>(){}); ... Both of these construct an object by calling the exact same deserialization process. So the only difference between these two calls is whether you're making a static (JavaType) or dynamic (TypeReference) reference to the type.
🌐
Java Guides
javaguides.net › 2023 › 10 › convert-json-string-to-map-in-java.html
Convert JSON string to Map in Java
October 26, 2023 - Jackson offers a powerful and efficient means of converting between JSON strings and Java Maps, allowing for flexible data processing within Java applications.
🌐
Educative
educative.io › answers › how-to-convert-a-json-string-to-a-map-using-jackson
How to convert a JSON string to a map using Jackson
Use the method readValue() of the ObjectMapper class, which takes in a JSON string and the class the string will be converted to. public <T> T readValue(String content, Class<T> valueType) String content: JSON string.
Find elsewhere
🌐
DevQA
devqa.io › map-json-string-to-java-object
How to Map a JSON String to a Java Object
July 11, 2023 - To begin, let’s create a simple Java class representing the structure of the JSON object we want to map. For this example, let’s assume we have a JSON object representing a person: public class Person { private String name; private int age; private String email; // Default constructor (required by JSON libraries) public YourClass() { } // getters and setters }
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-json-string-to-map
Convert JSON String to Map using Jackson
October 14, 2022 - try { // JSON string String json ...\"],\"admin\":true}"; // convert a JSON string to Java Map Map<String, Object> map = new ObjectMapper().readValue(json, Map.class); // print map keys and values for (Map.Entry<String, Object> ...
🌐
Baeldung
baeldung.com › home › json › convert json to a map using gson
Convert JSON to a Map Using Gson
January 8, 2024 - We can configure Gson to parse our map differently, then, by implementing a JsonDeserializer: public class StringDateMapDeserializer implements JsonDeserializer<Map<String, Date>> { private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); @Override public Map<String, Date> deserialize(JsonElement elem, Type type, JsonDeserializationContext jsonDeserializationContext) { return elem.getAsJsonObject() .entrySet() .stream() .filter(e -> e.getValue().isJsonPrimitive()) .filter(e -> e.getValue().getAsJsonPrimitive().isString()) .collect( Collectors.toMap( Map.Entry::getKey, e -> formatDate(e.getValue()))); } private Date formatDate(Object value) { try { return format(value.getAsString()); } catch (ParseException ex) { throw new JsonParseException(ex); } } }
🌐
Javatpoint
javatpoint.com › convert-json-to-map-in-java
Convert JSON to Map in Java - Javatpoint
Java Program to swap two string variables without using third or temp variable.
🌐
Baeldung
baeldung.com › home › json › reading json documents as maps and comparing them
Reading JSON Documents as Maps and Comparing Them | Baeldung
January 17, 2024 - In this article, we looked at comparing two JSON documents in Java. We looked at different ways to convert the JSON documents to Maps and then compared them using Guava’s Maps.difference() method.
🌐
Codez Up
codezup.com › home › best way to convert json to map in java
Best Way to Convert JSON to Map in Java | Codez Up
September 15, 2021 - We can also use the GSON for converting the JSON string to Map in Java.
🌐
Attacomsian
attacomsian.com › blog › gson-convert-json-string-to-map
Convert JSON String to and from Map using Gson
November 30, 2019 - To convert a JSON string to a Java Map with the same properties and keys, you can use the fromJson() method from Gson:
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › java json › java: convert json to a map
Java: Convert JSON to a Map - Apps Developer Blog
March 22, 2024 - This code demonstrates how to convert a JSON string to a Map<String, String> using Gson in Java.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › convert hashmap to json object in java
Convert Hashmap to JSON Object in Java | Baeldung
January 8, 2024 - On the other hand, JavaScript Object Notation (JSON) is a popular data interchange format commonly used to transmit data between a server and a web application. In modern software development, it’s common to encounter scenarios where data needs to be converted between different formats. One such scenario is converting a Map to JSON format. In this tutorial, we’ll explore three ways to convert a Map to JSON format. ... Map<String, String> data = new HashMap<>(); data.put("CS", "Post1"); data.put("Linux", "Post1"); data.put("Kotlin", "Post1");
🌐
Reddit
reddit.com › r/javahelp › string with json inside to hashmap (instead to objects)
r/javahelp on Reddit: String with JSON inside to HashMap (instead to objects)
March 17, 2020 -

I have a very complex JSON in String format so I don't want to create all necessary Java Classes because It would make my project very large, I just want to get one specific property from that JSON so my intention is to pass it to HashMap. This way I could get that property without creating any Java classes, is there any way to do that?

Thanks.

Json example (simplified):

[{ "line": 1, "elements": [{ "start_timestamp": "2020-03-13T12:14:35.340Z", "before": [{ "result": { "error_message": "org.openqa.selenium.NoSuchElementException: asdfasdf", "duration": 35995000000, "status": "failed" }, "match": { "location": "Cucumber.Tarragona.Integrados.Hooks.GeneralHooks.setup(io.cucumber.java.Scenario)" } }], "line": 4, "name": "Alta escala", "description": "", "id": "alta-escala;alta-escala", "after": [{ "embeddings": [{ "data": "iVBORw0KGgoAAA", "Something": "more..." }] }] }] }]

I tried:

ObjectMapper mapper = new ObjectMapper();Map<String, String> map = mapper.readValue(reportJson, new TypeReference<Map<String, String>>() {}); //https://mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/ <-- reference

I get this error:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of \java.util.LinkedHashMap<java.lang.Object,java.lang.Object>\ out of START_ARRAY token at [Source: (StringReader); line: 1, column: 1] at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1445) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1219) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1129) at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:639) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:360) at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4218) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3214) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3197) at TestlinkAPI.TestlinkApiDemo.TestLinkConnector.executeKatalonSpecificTestCase(TestLinkConnector.java:605) at TestlinkAPI.TestlinkApiDemo.TestLinkConnector.main(TestLinkConnector.java:218)\``

Top answer
1 of 3
2

This is method to read Map from json string using Jackson:

public final class JsonUtils {
    public static <T> Map<String, T> readMap(String json) throws Exception {
        if (json == null)
            return null;

        ObjectReader reader = new ObjectMapper().readerFor(Map.class);
        MappingIterator<Map<String, T>> it = reader.readValues(json);

        if (it.hasNextValue()) {
            Map<String, T> res = it.next();
            return res.isEmpty() ? Collections.emptyMap() : res;
        }

        return Collections.emptyMap();
    }
}

This is how to read Map from json using given utilit method:

Map<String, String> map = flatMap(new LinkedHashMap<>(), "", JsonUtils.readMap(json));

And finally, this is how to transfrom Map into required Map (probably this could be done within Jackson engine, with provided custom deserializers or so, but I do not know exactly how, and thats why it is easier to me to implement it manually):

public static Map<String, String> flatMap(Map<String, String> res, String prefix, Map<String, Object> map) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        String key = prefix + entry.getKey();
        Object value = entry.getValue();

        if (value instanceof Map)
            flatMap(res, key + '.', (Map<String, Object>)value);
        else
            res.put(key, String.valueOf(value));
    }

    return res;
}
2 of 3
1

Jackson JSON is a pretty cool library which does this for you. I wrote a quick example below but you should be able to apply this to your JSONObject.

Let's say you have A.class with property B.class who in turn has a nested property C.class

@JsonPropertyOrder({ "b" })
class A {
    @JsonProperty("b")
    public B b;

    @JsonProperty("b")
    public B getB() {
        return b;
    }

    @JsonProperty("b")
    public void setB(B b) {
        this.b = b;
    }
}

@JsonPropertyOrder({ "c" })
class B {
    @JsonProperty("c")
    public C c;

    @JsonProperty("c")
    public C getC() {
        return c;
    }

    @JsonProperty("c")
    public void setC(C c) {
        this.c = c;
    }
}

@JsonPropertyOrder({ "d" })
class C {
    @JsonProperty("d")
    public String d;

    @JsonProperty("d")
    public String getD() {
       return d;
    }

    @JsonProperty("d")
    public void setD(String d) {
        this.d = d;
    }
}

You can convert a nested JSONObject {"b":{"c":{"d":"test"}}} into A.class like this:

C c = new C();
c.setD("test");

B b = new B();
b.setC(c);

JSONObject obj = new JSONObject();
obj.put("b", b);
String jsonAsString = new Gson().toJson(obj);

A a = mapper.readValue(jsonAsString, A.class);

Similarly you should be able to convert your JSONObject into any type you want. Hope this helps

🌐
Stack Overflow
stackoverflow.com › questions › 49820057 › converting-json-string-to-map
java - Converting json string to map - Stack Overflow
Copystatic final String JSON_VAL="{\"A\":[{\"B\":[{\"C\":[{\"D1\":\"V1\",\"D2\":\"X1\",\"D3\":\"Y1\",\"D4\":\"Z1\"},{\"D1\":\"V2\",\"D2\":\"X2\",\"D3\":\"Y2\",\"D4\":\"Z2\"}]}]}]}"; final ObjectMapper mapper = new ObjectMapper(); final Wraper wraper = mapper.readValue(JSON_VAL, Wraper.class); final Map<String,List<String>> map = new HashMap<>(); Arrays.stream(wraper.a).forEach(a -> { Arrays.stream(a.b).forEach(b -> { final List<String> d1 = new ArrayList<>(); final List<String> d2 = new ArrayList<>(); final List<String> d3 = new ArrayList<>(); final List<String> d4 = new ArrayList<>(); Arrays.