To convert your object in JSON with Jackson:

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter; 

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Answer from Jean Logeart on Stack Overflow
๐ŸŒ
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).
Top answer
1 of 11
714

To convert your object in JSON with Jackson:

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter; 

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
2 of 11
57

I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.

I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here.

For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl

Choose the version your project needs. (Typically you can go with the latest stable build).

Once they are imported in to your project's libraries, add the following import lines to your code:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";

ObjectMapper mapper = new ObjectMapper();
    
try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

The result should looks like this: {"firstName":"Sample","lastName":"User","email":"[email protected]"}

Discussions

How to convert strings that look like JSON to JSON objects
Greetings All, I am running into a problem where my JSON objects cease being JSON objects and become strings when I do set variable and get variable in order to have them in scope in the final (top) path where I am building my final JSON payload which causes formatting issues (See the red lines): ... More on community.make.com
๐ŸŒ community.make.com
2
0
November 17, 2024
Convert Java object to JSON without external library
Converting arbitrary objects to JSON isn't particularly easy, especially when there are full solutions already available. Personally, I use Gson, which is pretty easy to use. If the no external libraries is a HARD requirement, then your only choice would be to use reflection to get the names and values of the fields of the object to build the JSON string. You might have recursion problems if there are nested objects that create a circular loop, which complicates things. If you only have to serialize specific classes, then it would probably be easier to essentially hardcode the JSON string generation, and just call the appropriately getters to build the string. Basically, if it's only a few specific classes then you can write your own, if it's any arbitrary object then I highly recommend using a library, but if no libraries then I guess you could try homerolling your own JSON serializer with reflection. More on reddit.com
๐ŸŒ r/javahelp
12
May 1, 2020
How to convert the following json string to java object? - Stack Overflow
It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Convert JsonObject to String - Stack Overflow
If it is, you can simply call ... to get JSON text of theJSONObject. ... It looks like what people who land here 3+ years later are finding useful is not at all related to what was asked. And it also looks like the question is long past help at getting clarified. I believe the original question was that @JayZhang wanted to flatten the object, such that data was a string representation ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ convert java object to json without external library
r/javahelp on Reddit: Convert Java object to JSON without external library
May 1, 2020 -

I feel like an idiot, I mean, I have been programming for a few years, mostly C# and Java, but all the REST apis I made was built with .NET, so I had no need for it.

Well, I can't find how to convert a Java object to a JSON WITHOUT the need of an external library, anyone?

Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ convert-java-object-to-json-string-using-gson
Convert Java Object to Json String using GSON - GeeksforGeeks
July 11, 2025 - GSON: It is an open-source Java library which is used to serialize and deserialize Java objects to JSON.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-convert-a-java-object-to-json
How to convert a Java object to JSON
The Google GSONโ€‹ library is the most popular library used for converting Java objects to JSON. The code to get a JSON String out of an object is given below.
๐ŸŒ
Kodejava
kodejava.org โ€บ how-do-i-convert-java-object-to-json
How do I convert Java Object to JSON? - Learn Java by Examples
Call object.toString() method to get the JSON string. package org.kodejava.json; import org.json.JSONObject; import org.kodejava.json.support.Student; import java.util.Arrays; public class PojoToJSON { public static void main(String[] args) ...
๐ŸŒ
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 Java, it's common to work with JSON data, and an operation you'll frequently perform is converting a JSON object to a string representation.
๐ŸŒ
Squash
squash.io โ€บ how-to-convert-java-objects-to-json-with-jackson
How To Convert Java Objects To JSON With Jackson
The ObjectMapper class in the Jackson library provides methods to convert Java objects to JSON and vice versa. To convert a Java object to JSON, you can use the writeValueAsString() method of the ObjectMapper class. This method serializes the ...
๐ŸŒ
HKR Trainings
hkrtrainings.com โ€บ home โ€บ community โ€บ java โ€บ how can i convert string to json object in java?
How can I convert String to JSON object in Java? - Java - HKR Community
There are three rich open source libraries that allow you to convert String to JSON object efficiently and the name of the three libraries are given below: Gson Libraries(Comes From Google) JSON-Simple Libraries JACKSON Libraries ยท Before using any of the above libraries, you need to set the classpath of the relevant jar file. For Gson Libraries, you need to set the classpath of Gson.jar file and you can refer to this link http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm for downloading .
๐ŸŒ
Initial Commit
initialcommit.com โ€บ blog โ€บ convert-java-object-to-json
Convert Java object to JSON
P.S: Itโ€™s worth to mention that toJson() method accepts also Hashmap, ArrayList and Arrays. Another popular library is Jackson. In order to convert Java objects to JSON using Jackson, you have to include 3 libraries: jackson-annotations, ...
๐ŸŒ
Json2
json2.top โ€บ article โ€บ java-object-to-json-string.html
Java Object to JSON String | JSON2.Top
Discover various methods for converting Java objects to JSON strings in this comprehensive guide. Explore the usage of popular libraries like Jackson and Gson, as well as the native JSONObject, with detailed examples provided for each method. Simplify the process of handling JSON data in Java ...
๐ŸŒ
Medium
medium.com โ€บ @salvipriya97 โ€บ how-to-convert-java-pojo-to-json-using-jackson-2ef9b69c4f08
How to convert Java POJO to JSON using Jackson | by Priya Salvi | Medium
April 28, 2024 - We create an instance of the ... objects to JSON and vice versa. We use the writeValueAsString() method of the ObjectMapper instance to serialize the Person object to a JSON string....
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2022 โ€บ 03 โ€บ 3-examples-to-parse-json-in-java-using.html
3 ways to parse JSON String to Object in Java [Jackson, Gson, and json-simple Example]
You just need to use the ObjectMapper class, which provides the readValue() method. This method can convert JSON String to Java object, that's why it takes JSON as a parameter and the Class instance in which you want to parse your JSON.
Top answer
1 of 1
2

Why not use GeoTools to handle the input and output? Then your code becomes simply something like:

File inFile = new File("/home/ian/Data/states/states.shp");
File outFile = new File("/home/ian/Data/states/states.geojson");
if (outFile.exists()) {
  outFile.delete();
}
outFile.createNewFile();
// Read
DataStore inputDataStore = DataStoreFinder.getDataStore(
        Collections.singletonMap("url", URLs.fileToUrl(inFile)));

String inputTypeName = inputDataStore.getTypeNames()[0];
SimpleFeatureType inputType = inputDataStore.getSchema(inputTypeName);

FeatureSource<SimpleFeatureType, SimpleFeature>
        source = inputDataStore.getFeatureSource(inputTypeName);

FeatureCollection<SimpleFeatureType, SimpleFeature>
        inputFeatureCollection = source.getFeatures();

Map<String, Object> params = new HashMap<>();
params.put(GeoJSONDataStoreFactory.URLP.key, URLs.fileToUrl(outFile));
// Write
DataStore newDataStore = DataStoreFinder.getDataStore(params);

newDataStore.createSchema(inputType);
String typeName = newDataStore.getTypeNames()[0];

SimpleFeatureStore featureStore =
        (SimpleFeatureStore) newDataStore.getFeatureSource(typeName);

featureStore.addFeatures(inputFeatureCollection);
newDataStore.dispose();
inputDataStore.dispose();

}

If you don't want to export all the attributes of the shapefile features you need to modify newDataStore.createSchema(inputType); to use a new limited schema. This needs something like:

SimpleFeatureType outType = DataUtilities.createSubType(inputType, new String[] {"type","REFCAT"});
newDataStore.createSchema(outType);