I am using the org.json library and found it to be nice and friendly.

Example:

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject().put("key1", "value1"))
                  .toString();

System.out.println(jsonString);

OUTPUT:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
Answer from dku.rajkumar on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - The org.json.JSONObject is perhaps the most commonly used class for parsing a JSON boolean value in Java. Letโ€™s explore parsing different representations of boolean values. First, we create a JSONObject from a JSON string.
๐ŸŒ
Kodejava
kodejava.org โ€บ how-do-i-write-json-string-using-json-java-org-json-library
How do I write JSON string using JSON-Java (org.json) library? - Learn Java by Examples
June 2, 2024 - package org.kodejava.json; import org.json.JSONArray; import org.json.JSONObject; public class WriteJSONString { public static void main(String[] args) { JSONObject object = new JSONObject(); object.put("id", 1L); object.put("name", "Alice"); object.put("age", 20); JSONArray courses = new JSONArray(); courses.put("Engineering"); courses.put("Finance"); courses.put("Chemistry"); object.put("courses", courses); String jsonString = object.toString(2); System.out.println(jsonString); } } ... <dependencies> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency> </dependencies> Thank you. I was struggling with one-line JSON files. The indentFactor in toString(n) function saved me!
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ json โ€บ json_java_example.htm
JSON with Java
Following is another example that shows a JSON object streaming using Java JSONObject โˆ’ ยท import org.json.simple.JSONObject; class JsonEncodeDemo { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name","foo"); obj.put("num",new Integer(100)); obj.put("balance",new Double(1000.21)); obj.put("is_vip",new Boolean(true)); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); System.out.print(jsonText); } }
๐ŸŒ
W3Docs
w3docs.com โ€บ java
How to create JSON Object using String?
String jsonString = "{\"key1\": \"value1\", \"key2\": \"value2\"}"; JSONObject jsonObject = new JSONObject(jsonString); This code will create a JSONObject with the following contents: ... You can also use the org.json library to create a JSON ...
๐ŸŒ
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 ... # method for 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 ......
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ handling-json-files-with-java โ€บ lessons โ€บ creating-and-writing-json-data-with-java-using-jackson
Creating and Writing JSON Data with Java
Create Instances: Instantiate these classes and populate them with data. This involves initializing objects and setting field values to reflect the information you wish to serialize. Serialize to JSON: Use the Jackson library's ObjectMapper class to serialize these objects into a JSON string...
๐ŸŒ
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
You are saying you are trying to create JSON object, so it looks like you want to convert a Java object into JSON String right? If you are using Gson, you can use toJson() method as shown above.
Find elsewhere
Top answer
1 of 4
22

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:

JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();

for(int i = 0 ; i< list.size() ; i++)
{
    p = list.get(i);

    obj.put("id", p.getId());
    obj.put("title", p.getTitle());
    obj.put("date". new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
    obj.put("txt", getTrimmedText(p.getText()));

    arr.put(obj);

    obj = new JSONObject();
}

Now your JSON string will look something like this:

[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
 {"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"},
 ...]

Assuming that your NewsItem gettors return Strings. The JSONObject method put is overloaded to take primitive types also, so if, e.g. your getId returns an int, then it will be added as a bare JSON int. I'll assume that JSONObject.put(String, Object) calls toString on the value, but I can't verify this.

Now in javascript, you can use such a string directly:

var arr =
    [{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
     {"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"}];

for (i = 0; i < arr.length; i++)
    alert(arr[i].title); // should show you an alert box with each first title
2 of 4
1

The idea of the json object is the same as a dictionary/map where you have keys and values assigned to those keys, so what you want to construct would be something like this:

{"1": {"title": "my title", "date": "17-12-2011", "text": "HELLO!"}, "2": ....}

where the "1" is the id and the contents is another dictionary/map with the info.

lets say you assigned the object to a variable named my_map, now you will be able to handle it as:

 my_map.1.title
 my_map.3.text
 ...

to iterate over it just use:

for (info in my_map){
    data = my_map[info];
    //do what you need
}
๐ŸŒ
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 - // Convert JSON Array String into Java Array List String jsonArrayString = "[\"Russian\",\"English\",\"French\"]"; Gson googleJson = new Gson(); ArrayList javaArrayListFromGSON = googleJson.fromJson(arrayFromString, ArrayList.class); System.out.println(javaArrayListFromGSON); //Convert Java Plain Object into JSON Person personPojo = new Person(); personPojo.setFirstName("Sergey"); personPojo.setLastName("Kargopolov"); Gson gsonBuilder = new GsonBuilder().create(); String jsonFromPojo = gsonBuilder.toJson(personPojo); System.out.println(jsonFromPojo);
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-json-example
Java JSON Example
Java JSON example for beginners and professionals with examples of JSON with java, install json.simple, java json encode, java json encode using map, java json array encode, java json array encode using List, java json decode. Learn Java JSON example with array, object, schema, encode, decode, ...
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-generate-json-with-jsongenerator-in-java
How to Generate JSON with JsonGenerator in Java? - GeeksforGeeks
June 8, 2022 - OBJECT Key firstName: STRING Duke ... STRING JavaTown Key state: STRING JA Key postalCode: STRING 12345 Key phoneNumbers: ARRAY OBJECT Key type: STRING mobile Key number: STRING 111-111-1111 OBJECT Key type: STRING home Key number: STRING 222-222-2222 ... The object models that we created in the above examples can be written to a stream using the JsonWriter ...
Top answer
1 of 2
2

You will need to use JSONArray and JsonArrayBuilder to map these json arrays.

This is the code you need to use:

    String jsonString = new JSONObject()
        .put("data", new JSONObject()
            .put("nightclub", Json.createArrayBuilder()
                    .add("abcbc")
                    .add("ahdjdjdj")
                    .add("djdjdj").build())
            .put("restaurants", Json.createArrayBuilder()
                    .add("abcbc")
                    .add("ahdjdjdj")
                    .add("djdjdj").build())
            .put("response", "success"))
                    .toString();
2 of 2
1

You can use gson lib.

First create pojo object:

public class JsonReponse {

private Data data;

public Data getData() {
    return data;
}

public void setData(Data data) {
    this.data = data;
}

public class Data {

    private String reponse;
    private List<String> nightclub;
    private List<String> restaurants;

    public String getReponse() {
        return reponse;
    }

    public void setReponse(String reponse) {
        this.reponse = reponse;
    }

    public List<String> getNightclub() {
        return nightclub;
    }

    public void setNightclub(List<String> nightclub) {
        this.nightclub = nightclub;
    }

    public List<String> getRestaurants() {
        return restaurants;
    }

    public void setRestaurants(List<String> restaurants) {
        this.restaurants = restaurants;
    }
}

}

and next complite data and generate json:

    JsonReponse jsonReponse = new JsonReponse();
    JsonReponse.Data data = jsonReponse.new Data();
    data.setReponse("sucess");
    data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
    data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
    jsonReponse.setData(data);

    Gson gson = new Gson();
    System.out.println(gson.toJson(jsonReponse));
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ working-with-json-data-in-java
Working with JSON Data in Java - GeeksforGeeks
December 23, 2025 - Example: Create and Print JSON Object. ... import org.json.simple.JSONObject; public class JavaJsonEncoding { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("Full Name", "Ritu Sharma"); jsonObject.put("Roll No.", 1704310046); jsonObject.put("Tuition Fees", 65400); System.out.println(jsonObject); } }
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-json-example
Java JSON Example | DigitalOcean
August 4, 2022 - With code identical to the example and parsing a well-formed JSON file generated by NetBeans the code fails at runtime with: javax.json.stream.JsonParsingException: Unexpected char 60 at (line no=1, column no=1, offset=0). ... Help me understand why this new JSON api is better than jaxb, ObjectMapper, or Jackson? In your example above, if I want to create a JSON string I do what youโ€™ve shown above: jsonGenerator.write().write().write()โ€ฆetc.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62709947 โ€บ most-efficient-way-to-create-json-string-in-java
Most Efficient way to create JSON String in java - Stack Overflow
In fact, the expression as posted above is already the most efficient approach. ... Recommended read. ... <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> </dependency> ... <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency> Refer this https://www.geeksforgeeks.org/convert-java-object-to-json-string-using-jackson-api/
Top answer
1 of 2
23

Welcome to the wonderful world of \n breaking your parser.

\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.

@Test
public 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\",\"\"]}";
        s= s.replaceAll("\n", "\\n");
        JSONObject json = new JSONObject(s); 
    }

works fine.

Edit: looking at your code you are in luck. Some services sometimes add a crazy character to the start of the feed and it looks like this is what happened here. You just need to trim it from the string.

Example :

s = s.substring(s.indexOf("{")); 
2 of 2
2
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTest {

    public static void main(String[] args) throws JSONException {
        String str = "{\"hours\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\"]}";
        JSONObject jsonObject = new JSONObject(str);
        System.out.println(jsonObject);
    }
}

Output is : {"hours":["1","2","3","4","5","6","7","8","9","10","11"]}

๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ convert java object to json
Convert Java object to JSON - Tabnine
July 25, 2024 - Converting a Java Obj to a JSON string is simple using JACKSON or GSON API. In our examples, we provided the code to make it easy for you to reproduce in your IDE. ... Create a new project (Maven is recommended).