You can use some API, like Jackson, for creating JSON object and print it into string. First create a json ArrayNode for your items. Then for each string in your items, create an ObjectNode like this,

ObjectNode node = mapper.createObjectNode();
node.put("result", "xyz");

and add them to the ArrayNode. Finally you print the JSON object out.

Answer from thegreatleaf on Stack Overflow
Top answer
1 of 2
41

Well, you can't. As you said, you can represent arrays and dictionaries. You have two choices.

Represent the set as an array. Advantage: Converting from set to array and back is usually easy. Disadvantage: An array has an implied order, which a set doesn't, so converting identical sets to JSON arrays can create arrays that would be considered different. There is no way to enforce that array elements are unique, so a JSON array might not contain a valid set (obviously you could just ignore the duplicates; that's what is likely to happen anyway).

Represent the set as a dictionary, with an arbitrary value per key, for example 0 or null. If you just ignore the values, this is a perfect match. On the other hand, you may have no library support for extracting the keys of a dictionary as a set, or for turning a set into a dictionary.

In my programming environment, conversion between set and array is easier (array to set will lose duplicate values, which either shouldn't be there, or would be considered correct), so for that reason I would go with arrays. But that is very much a matter of opinion.

BUT: There is a big fat elephant in the room that hasn't been mentioned. The keys in a JSON dictionary can only be strings. If your set isn't a set of strings, then you only have the choice of using an array.

2 of 2
12

Don't try to represent sets in JSON. Do it when parsing the data instead.

Your JSON data should have a schema which specifies which fields should be treated as a set, or you may have a metadata embedded in the JSON data itself that describes when a list should be treated as a set (e.g. {"houses": {"_type": "set", "value": [...]}}) or with a naming convention.

Note that according to JSON standard, a JSON object can have duplicate keys. ECMA-404 wordings:

Objects

[...] The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs. These are all semantic considerations that may be defined by JSON processors or in specifications defining specific uses of JSON for data interchange.

AFAICD, nothing in the spec forbids non unique names, and there are many JSON parser implementations that can parse non unique object names. RFC 7159 discourages non unique names for interoperability, but specifically don't forbid it either, and goes on to list how various parsers have been seen handling non unique object names.

And ECMA 404 also doesn't require that array ordering be preserved:

Arrays

The JSON syntax does not define any specific meaning to the ordering of the values. However, the JSON array structure is often used in situations where there is some semantics to the ordering.

This wording allows applications to use arrays to represent sets if they so choose.

Discussions

java - Can't parse HashSet to JSONObject String - Stack Overflow
Here, you can see both a and b are strings, in the list both are inside double quotation marks but in the set it's not. I am using org.json.simple v1.1. ... Did you try to make your HashSet as a HashSet ? More on stackoverflow.com
🌐 stackoverflow.com
December 7, 2018
Convert Set to JSONArray in Java 8 - Code Review Stack Exchange
Declare your variables as late as possible (json). Declare your variables in the smallest possible scope (tempj). Method names in Java start with a lowercase letter. Don't declare throws Exception when your code doesn't actually do that. It is unusual that the languages set actually contains null. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 29, 2017
Converting JSON Data to a set of Java objects - Stack Overflow
Is there a tool that generates the JSON objects in Java when given JSON data? This tool would either assume one of the "popular" JSON library or would let you specify the JSON library to be used. For More on stackoverflow.com
🌐 stackoverflow.com
Can't get jdt language server to work on coc-java extensions for coc-nvim extension

Just idly wondering if it just works with YCM

More on reddit.com
🌐 r/vim
5
2
April 26, 2020
🌐
Java Guides
javaguides.net › 2019 › 07 › convert-set-to-json-array-using-jackson.html
Convert Set to JSON Array Using Jackson
July 21, 2019 - In this quick article, I will show how to convert a Set to JSON array using Jackson. Check out complete Jackson tutorial at Java Jackson JSON Tutorial with Examples. We are using Jackson library to convert Java Set to JSON array so let's add below Jackson dependency to your project's pom.xml.
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – serialize and deserialize a set
Gson - Serialize and Deserialize a Set
April 3, 2023 - Set<Item> itemSet = Set.of(new ...},{"id":3,"name":"item3"}] Java program to deserialize JSON to HashSet using Gson.fromJson() method and TypeToken....
Top answer
1 of 3
4
  • You should not catch exceptions and discard them silently. This code has no chance of throwing an exception, therefore you should just let the exception bubble up and let someone else catch it. If it should ever happen.
  • Your variable names don't express their intention. The word temp should not be used at all, you mix terminology between languages and locale. Sometimes you put the j at the beginning of the name, sometimes at the end; this is inconsistent.
  • Declare your variables as late as possible (json).
  • Declare your variables in the smallest possible scope (tempj).
  • Method names in Java start with a lowercase letter.
  • Don't declare throws Exception when your code doesn't actually do that.
  • It is unusual that the languages set actually contains null. So in general you should leave out the if (language != null) check.

After following all these hints, the code may look like this:

public String createLanguagesJson(Set<Locale> languages) {
    JSONArray array = new JSONArray();
    for (Locale language : languages) {
        array.put(new JSONObject()
                .put("lcode", language.toLanguageTag())
                .put("ldisplay", language.getDisplayName()));
    }

    return new JSONObject()
            .put("root", array)
            .toString();
}
2 of 3
1

I really suggest to keep this implementation nearly as it is. It is clear and direct.

Maybe you decompose the method into two methods.

Maybe you reduce scope of one variable (tempj).

Maybe you rename some artefacts.

public String toJSONString(Set<Locale> languageSet) throws Exception {

    JSONObject root = new JSONObject();

    try {

        JSONArray localeAsJSONObjectArray = new JSONArray();

        for (Locale locale : languageSet) {
            if (locale != null) {
                localeAsJSONObjectArray.put(toJSONObject(locale));
            }
        }

        root.put("root", localeAsJSONObjectArray);

    } catch (JSONException e) {
        //
    }

    return root.toString();
}

private JSONObject toJSONObject(Locale locale) {
    JSONObject localeAsJSONObject = new JSONObject();
    localeAsJSONObject.put("lcode", locale.toLanguageTag());
    localeAsJSONObject.put("ldisplay", locale.getDisplayName());
    return localeAsJSONObject;
}

Anything else will distort the intention. Introducing lambdas here will make me think that you want to make the algorithm fit to lambda as the direction should be vice versa: The used control structures should follow your algorithm.

You have to keep one thing in mind:

Lambdas and streams really make sense if you use ".parallelStream()" instead of ".stream()". Then your code will act in some parallel way with the Fork-Join-Thread-Pool and your code speeds up. Anything else is Old wine in new bottles. Occasionally lambdas seem to be more expressive. In other situations you will break your leg if you want to fit you algorithm to lambda and you loose expressiveness.

But to use ".parallelStream()" your code has to meet some not obvious requirements that is clear to those who already work with parallelism. Most of the time you are not able to simply change ".stream()" to ".prallelStream()". So most of the time you will not benefit from the new API.

If you still want to use lambdas I provide you an example that is surely not strcutral optimizied but that shows the elements to consider if you really want to benefit from parallelism.

public static String toJSONString(Set<Locale> languageSet) {

    JSONObject root = new JSONObject();

    JSONArray localeAsJSONObjectArray = new JSONArray();

    // synchronization, as putting may occur asynchronously. JSONArray itself is NOT synchronized. 

    Consumer<JSONObject> synchronizedJSONObjectAdder = jsonObject -> {

        synchronized (localeAsJSONObjectArray) {
            localeAsJSONObjectArray.put(jsonObject);
        }

    };

    // function that defines the transformation from a locale to a JSONObject.
    // no synchronization needed as every result only depends on the function parameter.

    Function<Locale, JSONObject> localeToJSONObjectFunction = locale -> {
        JSONObject localeAsJSONObject = new JSONObject();
        localeAsJSONObject.put("lcode", locale.toLanguageTag());
        localeAsJSONObject.put("ldisplay", locale.getDisplayName());

        // for debugging in which thread the transformation will be processed.

        System.out.println(Thread.currentThread().getName());

        return localeAsJSONObject;
    };

    // using parallel stream to address parallelism
    languageSet.parallelStream().filter(locale -> locale != null).map(localeToJSONObjectFunction).forEach(synchronizedJSONObjectAdder);

    root.put("root", localeAsJSONObjectArray);

    return root.toString();
}


public static void main(String[] args) throws Exception {
    toJSONString(new HashSet<>(Arrays.asList(Locale.getAvailableLocales())));
}
Find elsewhere
🌐
Blogger
javainspires.blogspot.com › home › coding › [jackson api examples] - how to convert java set object to/from json string using jackson?(serialize and de-serialize)
[Jackson API Examples] - How to Convert Java Set Object to/from JSON String using Jackson?(Serialize and De-serialize)
August 15, 2021 - package com.javainspires; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @author #JavaInspires * */ public class MainApp { public static void main(String[] args) throws IOException { // create a Set object Set<String> sampleSet = new HashSet<>(); sampleSet.add("C"); sampleSet.add("C++"); sampleSet.add("Java"); sampleSet.add("Python"); sampleSet.add("GoLang"); sampleSet.add("Kotlin"); // create object mapper class object ObjectMapper mapper = new ObjectMapper(); // convert set object to json string using th
🌐
Baeldung
baeldung.com › home › persistence › converting a jdbc resultset to json in java
Converting a JDBC ResultSet to JSON in Java | Baeldung
January 8, 2024 - The jOOQ framework (Java Object Oriented Querying) provides, among other things, a set of convenient utility functions to work with JDBC and ResultSet objects. First, we need to add the jOOQ dependency to our POM file: <dependency> <groupId>org.jooq</groupId> <artifactId>jooq</artifactId> <version>3.11.11</version> </dependency> After adding the dependency, we can actually use a single-line solution for converting a ResultSet to a JSON object:
🌐
Oracle
blogs.oracle.com › javamagazine › java-json-serialization-jackson
Looking for a fast, efficient way to serialize and share Java objects? Try Jackson.
Jackson can be used to automatically serialize this class to JSON so that it can, for example, be sent over the network to another service that may or may not be implemented in Java and that can receive JSON-formatted data. You can set up this serialization with a very simple bit of code, as follows:
🌐
Tabnine
tabnine.com › home › convert java object to json
Convert Java object to JSON - Tabnine
July 25, 2024 - The mobile/web app communicates with the RESTful web service via XML / JSON. In our example diagram above, our RESTful web service was designed using Java. Since Java objects are only understood by Java applications, we need to convert the Java object to JSON when creating a web service for the Android app.
🌐
Medium
medium.com › @bubu.tripathy › json-serialization-and-deserialization-in-java-2a3f08266b70
JSON Serialization and Deserialization in Java | by Bubu Tripathy | Medium
April 9, 2023 - In this example, we create a Java object of type MyObject and set its properties. We then create an instance of the ObjectMapper class, which is responsible for converting the Java object to JSON. We call the writeValueAsString() method of the ObjectMapper class, passing in the Java object ...
🌐
Javatpoint
javatpoint.com › convert-java-object-to-json
Convert Java object to JSON - javatpoint
Convert Java object to JSON with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › convert java into json and json into java. all possible examples.
Convert Java into JSON and JSON into Java. All Possible Examples. - Apps Developer Blog
March 25, 2024 - Google GSON library is a Java-based library that provides a simple way to convert Java objects into JSON (JavaScript Object Notation) format and vice versa. GSON library is developed by Google and it is an open-source project available on GitHub. GSON library provides a set of APIs to serialize ...
🌐
Baeldung
baeldung.com › home › java › java list › converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - We aim to convert this “articles” list into a JSON array. So, the expected output should be as follows: ... We’ll explore three different approaches in the following sections to accomplish the conversion task. Gson is a popular Java library developed by Google for working with JSON data since it provides a simple API for converting Java objects to JSON.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
If it is an array or collection, wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et al) then it is already wrapped. Otherwise, if it comes from one of the java packages, turn it into a string. And if it doesn't, try to wrap it in a JSONObject.
🌐
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.