简体   繁体   中英

How to convert a Java object to JSON object in Eclipse

My requirement is to convert a plain Java object to JSON format -

The Java object has following format -

Record Id: 168349200
 Name:  jane
 City:  abababa
 State:  ababab
 Insertion Date:  18/04/2017 10:16:17

I have gone through some tutorials and found that GSON library is a way to do it. I tried to install the gson jar in my Eclipse project (using Eclipse Mars Release (4.5.0)).

But when I do -

import com.google.gson.Gson

in the class where I want to do the conversion of the Java object to JSON it throws an exception.

I think I have not added the GSON jar file properly.

Can some one please help.

Thanks.

Try:

    Gson gson = new Gson();
    String jsonString = null;
    try {
        jsonString = gson.toJson(javaObject);
    } catch (Exception e) {
        e.printStackTrace();
    }

From Java Object to Json using ObjectMapper:

ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);

MyObject mObject = new MyObject();

String jsonObject ="";


mObject.setField1(value1);
mObject.setField2(value2);
mObject.setField3(value3);

try {
            jsonObject = objMapper.writeValueAsString(mObject);
            System.out.println(jsonObject); //You can then store it in a file

     } catch (JsonProcessingException e) {

            e.printStackTrace();
     }

You should add these imports:

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

And in the pom.xml these lines:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.5</version>
        </dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM