Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.


How should I structure my Java object?

Below is what your object model could look like. MOXy's JSON binding leverages JAXB annotations for mapping the domain model to JSON, so I have included those as well. JAXB implementations have default rules for mapping field/property names, but since your document differs from the default each field had to be annotated.

MyResult

package forum11001458;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="MyResult")
public class MyResult {

    @XmlElement(name="AccountID")
    private String accountID;

    @XmlElement(name="User")
    private User user;

    @XmlElement(name="Result")
    private Result result;

}

User

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class User {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Email")
    private String email;

}

Result

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class Result {

    @XmlElement(name="Course")
    private String course;

    @XmlElement(name="Score")
    private String score;

}

What Json library can I use for this?

Below is how you can use MOXy to do the JSON binding:

jaxb.properties

To use MOXy as your JAXB provider you need to include a file called jaxb.properties with the following entry in the same package as your domain model:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

Note how MOXy's JSON binding does not require any compile time dependencies. All the necessary APIs are available in Java SE 6. You can add the necessary supporting APIs if you are using Java SE 5.

package forum11001458;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyResult.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", "application/json");
        File json = new File("src/forum11001458/input.json");
        Object myResult = unmarshaller.unmarshal(json);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myResult, System.out);
    }

}

input.json/Output

{
   "MyResult" : {
      "AccountID" : "12345",
      "User" : {
         "Name" : "blah blah",
         "Email" : "[email protected]"
      },
      "Result" : {
         "Course" : "blah",
         "Score" : "10.0"
      }
   }
}
Answer from bdoughan on Stack Overflow
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ convert java objects to json with jackson
Convert Java Objects to JSON with Jackson - Mkyong.com
April 24, 2024 - package com.mkyong.json.jackson.tips; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json.model.Person; public class ConvertObjectToJsonExample2 { public static void main(String[] args) { String json = "{\"name\": \"mkyong\", \"age\": 20}"; ObjectMapper om = new ObjectMapper(); try { // covert JSON to Java object Person person = om.readValue(json, Person.class); // output: Person{name='mkyong', age=20} System.out.println(person); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } ... This example uses Jackson to convert a Java object Person to a JSON string and write it in a file named person.json.
๐ŸŒ
Json2CSharp
json2csharp.com โ€บ code-converters โ€บ json-to-pojo
Convert JSON to POJO Objects in Java Online
Convert any JSON to POJO objects in Java online. Json2CSharp is a free parser and converter that will help you generate Java classes from a JSON object and use Jackson librairies to deserialize into a Java class.
Discussions

Converting Java objects to JSON with Jackson - Stack Overflow
I just missing the part how I can convert the Java object to JSON with Jackson: More on stackoverflow.com
๐ŸŒ stackoverflow.com
arrays - How to convert jsonString to JSONObject in Java - Stack Overflow
-2 Convert a String which is in JSON Format to a JSON Object in java More on stackoverflow.com
๐ŸŒ stackoverflow.com
Converting JSON data to Java object - Stack Overflow
The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert a Java Object to JsonObject type of couch base?
The example i found at โ€œhttp://docs.couchbase.com/developer/java-2.0/documents-bulk.htmlโ€ is going though each property in java class and adding it to JsonObject. is there a way that we can convert a Java object into JsonObject without traversing through all properties manually and adding ... More on couchbase.com
๐ŸŒ couchbase.com
0
0
June 24, 2015
Top answer
1 of 6
10

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.


How should I structure my Java object?

Below is what your object model could look like. MOXy's JSON binding leverages JAXB annotations for mapping the domain model to JSON, so I have included those as well. JAXB implementations have default rules for mapping field/property names, but since your document differs from the default each field had to be annotated.

MyResult

package forum11001458;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="MyResult")
public class MyResult {

    @XmlElement(name="AccountID")
    private String accountID;

    @XmlElement(name="User")
    private User user;

    @XmlElement(name="Result")
    private Result result;

}

User

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class User {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Email")
    private String email;

}

Result

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class Result {

    @XmlElement(name="Course")
    private String course;

    @XmlElement(name="Score")
    private String score;

}

What Json library can I use for this?

Below is how you can use MOXy to do the JSON binding:

jaxb.properties

To use MOXy as your JAXB provider you need to include a file called jaxb.properties with the following entry in the same package as your domain model:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

Note how MOXy's JSON binding does not require any compile time dependencies. All the necessary APIs are available in Java SE 6. You can add the necessary supporting APIs if you are using Java SE 5.

package forum11001458;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyResult.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", "application/json");
        File json = new File("src/forum11001458/input.json");
        Object myResult = unmarshaller.unmarshal(json);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myResult, System.out);
    }

}

input.json/Output

{
   "MyResult" : {
      "AccountID" : "12345",
      "User" : {
         "Name" : "blah blah",
         "Email" : "[email protected]"
      },
      "Result" : {
         "Course" : "blah",
         "Score" : "10.0"
      }
   }
}
2 of 6
7

Googles GSON is a really nice json lib. This is from the previous link and it basically outlines some of its functionality.

๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ jackson โ€บ intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - This tutorial focuses on understanding the Jackson ObjectMapper class and how to serialize Java objects into JSON and deserialize JSON string into Java objects.
๐ŸŒ
Site24x7
site24x7.com โ€บ tools โ€บ json-to-java.html
JSON to JAVA Code Generator: Site24x7 Tools
Free code generator which converts your JSON (JavaScript Object Notation) schema into Java Object. The JSON keys are converted to private variables with getter setter methods for them. The inner objects in JSON are converted as inner classes in Java Object.
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]"}

Find elsewhere
๐ŸŒ
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 JSON string containing the same data as in the previous example. We then call the `readValue()` method of the `ObjectMapper` class, passing in the JSON string and the class of the Java object we want to deserialize to.
๐ŸŒ
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
Serialize to JSON: Use the Jackson library's ObjectMapper class to serialize these objects into a JSON string, ready for storage or transmission. These steps form the foundation of translating structured class-based data into a JSON format, seamlessly bridging Java applications with JSON data ...
๐ŸŒ
Jsonschema2pojo
jsonschema2pojo.org
jsonschema2pojo
Generate Plain Old Java Objects from JSON or JSON-Schema. ... For each property present in the 'properties' definition, we add a property to a given Java class according to the JavaBeans spec.
Top answer
1 of 15
371

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }
    
    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

See also:

  • Json.org - Introduction to JSON
  • Gson User Guide - Introduction to Gson
2 of 15
52

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.

๐ŸŒ
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties. Created by Zack Grossbart. Get the source code. Big thanks owed to the team behind JSONLint.
๐ŸŒ
Oracle
blogs.oracle.com โ€บ javamagazine โ€บ java-json-serialization-jackson
Looking for a fast, efficient way to serialize and share Java objects? Try Jackson.
What happens when you want to go the other way? Fortunately, the ObjectMapper provides a reading API as well as a writing API. Here is how the reading API works; this example also uses Java 17 text blocks, by the way. var json = """ { "firstName" : "Grant", "lastName" : "Hughes", "age" : 19 }"""; var mapper = new ObjectMapper(); try { var grant = mapper.readValue(json, Person.class); System.out.println(grant); } catch (JsonProcessingException e) { e.printStackTrace(); }
๐ŸŒ
Couchbase
couchbase.com โ€บ java sdk
How to convert a Java Object to JsonObject type of couch base? - Java SDK - Couchbase Forums
June 24, 2015 - The example i found at โ€œhttp://docs.couchbase.com/developer/java-2.0/documents-bulk.htmlโ€ is going though each property in java class and adding it to JsonObject. is there a way that we can convert a Java object into JsonObject without traversing through all properties manually and adding ...
๐ŸŒ
JSON Formatter
jsonformatter.org โ€บ 0564a5
pojo
95% of API Uses JSON to transfer data between client and server. This tools can works as API formatter. Supports JSON Graph View of JSON String which works as JSON debugger or corrector and can format Array and Object.
๐ŸŒ
JSONLint
jsonlint.com โ€บ json-to-java
JSON to Java Converter - Generate POJO Classes Online | JSONLint | JSONLint
This tool automatically generates Java class definitions from your JSON data. It infers types from values, handles nested objects, and supports popular libraries like Lombok, Jackson, and Gson.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ parse-json-java
How to parse JSON in Java - GeeksforGeeks
December 23, 2025 - Java does not have built-in JSON parsing support before Java 9, so external libraries are commonly used. In this article, we use JSON.simple, a lightweight and easy-to-use library. Parse JSON from strings or files. Create JSON objects and arrays.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javaee โ€บ 7 โ€บ api โ€บ javax โ€บ json โ€บ JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
Returns the array value to which the specified name is mapped. This is a convenience method for (JsonArray)get(name) to get the value. ... the array value to which the specified name is mapped, or null if this object contains no mapping for the name