Get api param from json file java with arrays - java

I have a json a file that doesnt contain only my api i am new to json and trying to get my api parameters from the file
"operators": {
"tez" : {
"api": "www.my-tour.com/search/getResult",
"parameters": [
{
"country": "Canada",
"queryParameters": {
"priceMin": ["0"],
"priceMax":["150000"],
"currency":["5561"],
"nightsMin":[1,2,3,4,5,6,7,8,9,10,11,12,13],
"nightsMax":[1,2,3,4,5,6,7,8,9,10,11,12,13]
In my app operator is just simple the company that owns the api so i have many operators so "tez" is the name of the company and below is its api and param
#Override
public JsonObject fetchData(String url) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, 20);
for (int i = 1; i <= 180; i++) {
String formattedDate = dateFormat.format(calendar);
url += "&after=" + formattedDate + "&before=" + formattedDate;
// how can i get the api iteratively to get all api param
JsonObject json = new JsonObject().getJsonObject("tez");
// TODO call eternal API here
JSONParser parser = new JSONParser();
JsonObject a = null;
try {
FileReader fileReader = new FileReader("\\home\\user\\MyProjects\\MicroserviceBoilerPlate\\src\\config\\local_file.json");
a = (JsonObject) parser.parse(fileReader);
} catch (Exception e1) {
e1.printStackTrace();
}
This above is what i am came up with but its not correct im not able to access the json file and how can i iterate through the parameters so i can add them to the api
www.my-tour.com/search/getResult?priceMin=0&priceMax=150000&currency=+value &nightsMin= + value &nightsMax=+values etc
Note: This is a vertx app and i am using JsonObject and other Json specific api's

You could just make an object of the JSON properties in the file
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
#JsonIgnoreProperties(ignoreUnknown = true)
public class TezModel {
public Operators operators;
public String getApi() {
return operators.tez.api;
}
public List<String> getPriceMin() {
return operators.tez.parameters.get(0).queryParameters.priceMin;
}
public List<String> getPriceMax() {
return operators.tez.parameters.get(0).queryParameters.priceMax;
}
public List<String> getCurrency() {
return operators.tez.parameters.get(0).queryParameters.currency;
}
public List<Integer> getNightsMin() {
return operators.tez.parameters.get(0).queryParameters.nightsMin;
}
public List<Integer> getNightsMax() {
return operators.tez.parameters.get(0).queryParameters.nightsMax;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Operators {
public Tez tez;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Tez {
public String api;
public List<Parameters> parameters;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Parameters {
public String country;
public QueryParameters queryParameters;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class QueryParameters {
public List<String> priceMin;
public List<String> priceMax;
public List<String> currency;
public List<Integer> nightsMin;
public List<Integer> nightsMax;
}
}
And then you could add your parameters to a string using jackson databind
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TezModel tezModel = mapper.readValue(new File("local_file.json"), TezModel.class);
String api = tezModel.getApi()+ "+priceMin="
+ tezModel.getPriceMin().get(0)
+ "&priceMax=" + tezModel.getPriceMax().get(0)
+ "&currency=+" + tezModel.getCurrency().get(0)
+ "nightsMin=" + tezModel.getNightsMin().get(0)
+ "nightsMax=" + tezModel.getNightsMax().get(0);
System.out.println(api);
}

Related

Deserialize array of strings to csv

I have a json payload with:
"host_names": [
"www.host1.com",
"www.host2.com"
]
How can I deserialize this as a csv using Jackson - e.g.:
"www.host1.com,www.host2.com"
Previously I was deserializing this as a String[] but I can't persist that with hibernate, so now I'm trying to deserialize it as a csv.
EDIT:
I want to use annotations to turn the json array into a string, where each element of the array is separated by a comma. Perhaps something like #JsonRawValue. The goal is to then persist the value to a data via hibernate.
public static void main(String[] args) {
String jsonStr = "{\"host_names\": [\r\n" +
" \"www.host1.com\",\r\n" +
" \"www.host2.com\"\r\n" +
"]}";
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray hostNames = jsonObject.getJSONArray("host_names");
String result = "";
for(int i=0;i<hostNames.length(); i++) {
if(!result.isEmpty())
result = result+",\""+hostNames.getString(i)+"\"";
else
result = "\""+hostNames.getString(i)+"\"";
}
System.out.println(result);
}
result
"www.host1.com","www.host2.com"
Other approach based on annotation
Create a class
class Server{
#JsonProperty(value = "host_names")
private List<String> hostNames;
public List<String> getHostNames() {
return hostNames;
}
public void setHostNames(List<String> hostNames) {
this.hostNames = hostNames;
}
}
Now use com.fasterxml.jackson.databind.ObjectMapper to parse the JSON into this class
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String jsonStr = "{\"host_names\": [\r\n" +
" \"www.host1.com\",\r\n" +
" \"www.host2.com\"\r\n" +
"]}";
ObjectMapper mapper = new ObjectMapper();
Server server = mapper.readValue(jsonStr, Server.class);
System.out.println(server.getHostNames());
}
output
[www.host1.com, www.host2.com]
You can slightly modify your setter / getter for host_names property as
Bean Class
public class Server {
#JsonProperty("host_names")
private List<String> hostNames;
#JsonGetter("host_names")
public String getHostNames() {
return String.join(",", hostNames);
}
#JsonSetter("host_names")
public void setHostNames(List<String> hostNames) {
this.hostNames = hostNames;
}
}
Main Method
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Server server = mapper.readValue("{\"host_names\":[\"www.host1.com\",\"www.host2.com\"]}", Server.class);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(server);
System.out.println(json);
}
Output
{
"host_names" : "www.host1.com,www.host2.com"
}
This way you can serialize as comma separated string, and array of string while deserializing.
Another Solution using #JsonValue Annotation.
Define your bean class as:
public class Server {
#JsonProperty("host_names")
private List<String> hostNames;
#JsonValue
public String hostNames() {
return String.join(",", hostNames);
}
public List<String> getHostNames() {
return hostNames;
}
public void setHostNames(List<String> hostNames) {
this.hostNames = hostNames;
}
}
Main Method
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Server server = mapper.readValue("{\"host_names\":[\"www.host1.com\",\"www.host2.com\"]}", Server.class);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(server);
System.out.println(json);
}
Output
"www.host1.com,www.host2.com"
This method will only be useful if your bean class has no other fields to serialize.

Determine appropriate class based on property existence when reading JSON

Assuming I have two types of responses from a service - positive and negative. They have JSON format.
When I use Jackson API to create the corresponding java objects I have to write the code like this:
import com.fasterxml.jackson.databind.ObjectMapper;
private ObjectMapper objectMapper = new ObjectMapper();
String json = ... // JSON received from a service
ServiceResponse response = objectMapper.readValue(json, ServiceResponse.class);
// Analyze the response
if (response instanceof PositiveServiceResponse) {
...
}
...
The problem is that both types of responses have nothing in common. There is no "type" property.
Otherwise I could use Vehicle-Car-Truck example from https://www.baeldung.com/jackson-inheritance
Sample positive response:
{
"city": "c",
"street": "s"
}
Negative response:
{
"errorMsg": "error",
"errorCode": "572"
}
The NegativeServiceResponse contains errorCode property. Is it possible to "tell" the Jackson API to create and instance of NegativeServiceResponse class if JSON contains the property, and an instance of PositiveServiceResponse otherwise?
Of course I can parse the JSON using low-level mechanisms (JsonNode etc.), but is there a more elegant solution?
It is possible to do. You need to create a Container class for both positive and negative response. See below, let me know if it works.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
class Solution {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping();
Positive positive = new Positive(1);
Negative negative = new Negative(-1);
Response response = new Response(positive, negative);
String json = objectMapper.writeValueAsString(response);
Response output = objectMapper.readValue(json, Response.class);
System.out.println(output.negative);
System.out.println(output.positive);
//practically, when you have only either positive or negative
Response response2 = new Response();
response2.setPositive(positive);
String json2 = objectMapper.writeValueAsString(response2);
//or String json2 = "{\"positive\":{\"code\":1}};
System.out.println(json2);
Response output2 = objectMapper.readValue(json2, Response.class);
System.out.println(output2.positive);
System.out.println(output2.negative);
}
}
Output:
Negative{otherCode=-1}
Positive{code=1}
{"positive":{"code":1},"negative":null}
Positive{code=1}
null
Response classes:
class Response {
Positive positive;
Negative negative;
public Response() {
}
public Response(Positive positive, Negative negative) {
this.positive = positive;
this.negative = negative;
}
public boolean isPositive() {
return positive != null;
}
public void setPositive(Positive positive) {
this.positive = positive;
}
public void setNegative(Negative negative) {
this.negative = negative;
}
public Positive getPositive() {
return positive;
}
public Negative getNegative() {
return negative;
}
}
class Positive {
private int code;
public Positive() {
}
public Positive(int code) {
this.code = code;
}
public int getCode() {
return code;
}
#Override
public String toString() {
return "Positive{" +
"code=" + code +
'}';
}
}
class Negative {
private int otherCode;
public Negative() {
}
public Negative(int otherCode) {
this.otherCode = otherCode;
}
public int getOtherCode() {
return otherCode;
}
#Override
public String toString() {
return "Negative{" +
"otherCode=" + otherCode +
'}';
}
}
Assuming you have class hierarhy like following
class ServiceResponse {}
class PositiveServiceResponse extends ServiceResponse { public String city; public String street; }
class NegativeServiceResponse extends ServiceResponse { public String errorMsg; public String errorCode; }
Then you create deserializer:
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
class ServiceResponseDeserializer extends StdDeserializer<ServiceResponse> {
protected ServiceResponseDeserializer() {
super(ServiceResponse.class);
}
#Override
public ServiceResponse deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
ObjectMapper mapper = (ObjectMapper) p.getCodec();
ObjectNode root = mapper.readTree(p);
if (root.get("errorMsg") != null) { // found negative token
NegativeServiceResponse result = new NegativeServiceResponse();
result.errorCode = root.get("errorCode").asText();
result.errorMsg = root.get("errorMsg").asText();
return result;
// OR (shorter but less efficient due to object-back-to-string conversion)
return mapper.readValue(root.toString(), NegativeServiceResponse.class);
} else {
return mapper.readValue(root.toString(), PositiveServiceResponse.class);
}
}
}
and use like following
#Test
public void testJackson() throws IOException {
SimpleModule module = new SimpleModule("ServiceResponseModule")
.addDeserializer(ServiceResponse.class, new ServiceResponseDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
ServiceResponse positive = mapper.readValue(
"{ \"city\": \"c\", \"street\": \"s\" }", ServiceResponse.class);
assertTrue(positive instanceof PositiveServiceResponse);
ServiceResponse negative = mapper.readValue(
"{ \"errorMsg\": \"error\", \"errorCode\": \"572\" }", ServiceResponse.class);
assertTrue(negative instanceof NegativeServiceResponse);
}

How to extract array values within nested JSON data

I have JSON data in the following format:
{
"data": {
"id": 14810798216415,
"name": "crescentbahuman.com",
"is_organization": true,
"email_domains": [
"crescentbahuman.com"
]
}
}
I want to get the string in the "email_domains" field. I wrote the following code as my attempt:
JSONObject dataObject2= (JSONObject)jsonObject2.get("data");
long id = (long) dataObject2.get("id");
System.out.println("worksapce id is: " + id);
String name = (String) dataObject2.get("name");
System.out.println("The worksapce name is: " + name);
boolean is_organization = (boolean) dataObject2.get("is_organization");
System.out.println("The workspace is organization: " + is_organization);
JSONArray email_domains = (JSONArray) jsonObject2.get("email_domains");
Iterator<String> iterator = email_domains.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
In this code to get "email_domains" only, a JSON Array object is created that get data from the JSON object and then its iterator is used to get values from within the array. However, it throws a NullPointerException on this line:
Iterator<String> iterator = email_domains.iterator();
I am stuck due to this problem. Can anyone kindly suggest a solution?
If you are using the JSON library from http://www.json.org/java/, then you should not be using JSONObject.get() so frequently. The library has other methods to get specific types, such as getLong(), getJSONArray(), and so forth. For your case with the "email_domains" field, you should try:
JSONArray array = dataObject2.getJSONArray("email_domains");
String value = array.getString(0);
org.json.JSONArray email_domains = (org.json.JSONArray) json.get("email_domains");
int length = email_domains.length();
for(int i = length-1; i > 0; i--) {
org.json.JSONObject jsonData = (org.json.JSONObject) email_domains.get(i);
System.out.println(jsonData);
}
My solution? I hate to be someone to offer a solution in another library... but look into google collections and the Gson helper. It can turn your Json into a map for you, and then back to json again when you are done.
Map map = gson.fromJson(jsonText, Map.class);
JsonArray's can then be cast into List's
try this to fetch "email_domains"
JSONArray email_domains = ((JSONArray) jsonObject).get("email_domains");
or
JSONObject obj = new JSONObject(jsonObject.Tostring());
JSONArray email_domains = obj.optJSONArray("email_domains");
"email_address" is JSONArray so we need to fetch this like
JSONArray email_domains = (JSONArray) dataObject2.getJSONArray("email_domains");
email_domains.get(0); // this will return crescentbahuman.com
Use this implementation
import java.lang.reflect.Field;
import java.util.List;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonConvertor {
private static GsonBuilder gsonBuilder;
private static Gson gson;
private JsonConvertor() {
}
public static Object fromJson(String json, Class clz)
{
gson=new Gson();
return gson.fromJson(json,clz);
}
public static String toJson(Object obj) {
gsonBuilder = new GsonBuilder();
gsonBuilder = gsonBuilder
.addSerializationExclusionStrategy(new CustomIclusionStrategy(
obj.getClass()));
gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
}
class CustomIclusionStrategy implements ExclusionStrategy {
private Class classToIclude;
private Field[] declaredFields;
private List<FieldAttributes> fields;
public CustomIclusionStrategy(List<FieldAttributes> fields) {
this.fields = fields;
}
public CustomIclusionStrategy(Class classToIclude) {
this.classToIclude = classToIclude;
this.declaredFields=classToIclude.getDeclaredFields();
}
// called only if shouldSkipClass returns false
#Override
public boolean shouldSkipField(FieldAttributes f) {
try {
classToIclude.getSuperclass().getDeclaredField(f.getName());
System.out.println(f.getName());
return true;
} catch (Exception e) {
}
return false;
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
// if returns false shouldSkipField will be called, otherwise
//shouldSkipField will not be called
return false;
}
}
public class Org {
private Data data;
public Org(Data data) {
super();
this.data = data;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String toJson()
{
return JsonConvertor.toJson(this);
}
public static void main(String[] args) {
String json="{\"data\": {\"id\":\"1\",\"name\":\"org1\",\"is_organization\":true,\"email_domains\": [\"email1\",\"email2\",\"email3\",\"email4\"]}}";
Org o=(Org) JsonConvertor.fromJson(json, Org.class);
System.out.println(o.getData().getEmail_domains());
}
}

GSON getting arrays [duplicate]

I have a basic JSON with all data contained in an array. One would think that it would be simple to retreive a value out of the array, but after multiple hours of trying every different method of parsing I could think of I'm completely lost. Any help would be greatly appreciated. Sorry for the horrid wording of this question.
I know I've attempted reading the JSON as an object using JsonReader and then parsing for the ID field. That would be my latest attempt, the code for the other attempts has already been deleted I'm afraid and I can't provide much information on said attempts
JsonReader reader = new JsonReader(new FileReader(Constants.VersJson));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
reader.beginArray();
if (name.equals("id")) {
System.out.println(reader.nextString());
Below I'll include a snippet of the JSON Array.
"versions": [
{
"id": "2.7",
"time": "2012-10-25T15:00:00+02:00",
"releaseTime": "2013-10-25T15:00:00+02:00",
"type": "Release"
},
{
"id": "2.6.4",
"time": "2011-12-2T14:01:07+02:00",
"releaseTime": "2013-12-2T14:01:07+02:00",
"type": "Develop"
},
{
"id": "2.5",
"time": "2010-11-24T21:05:00+02:00",
"releaseTime": "2013-11-25T01:04:05+02:00",
"type": "Develop"
Your json format is not correct which you have posted here
correct it for example
{
"versions":[
{
"id":"2.7",
"time":"2012-10-25T15:00:00+02:00",
"releaseTime":"2013-10-25T15:00:00+02:00",
"type":"Release"
},
{
"id":"2.6.4",
"time":"2011-12-2T14:01:07+02:00",
"releaseTime":"2013-12-2T14:01:07+02:00",
"type":"Develop"
}
]
}
First Define Classes you will get everything
public class Version {
private List<Versions> versions;
public List<Versions> getVersions() {
return versions;
}
public void setVersions(List<Versions> versions) {
this.versions = versions;
}
#Override
public String toString() {
return "Version [versions=" + versions + "]";
}
}
public class Versions {
private String id;
private String time;
private String releaseTime;
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getReleaseTime() {
return releaseTime;
}
public void setReleaseTime(String releaseTime) {
this.releaseTime = releaseTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Versions [id=" + id + ", time=" + time + ", releaseTime="
+ releaseTime + ", type=" + type + "]";
}
}
Finally you can parse the JSON as like here
JsonReader reader = new JsonReader(new FileReader(Constants.VersJson));
Gson gson = new Gson();
Version version = gson.fromJson(reader, Version.class);
i have also faced json array parsing using gson here is my code solved it
this is my reader class functions
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(myFile)));
System.out.println( reader);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(reader).getAsJsonArray();
ArrayList<JsonOperations> lcs = new ArrayList<JsonOperations>();
for(JsonElement obj : jArray )
{
JsonOperations cse = gson.fromJson( obj , JsonOperations.class);
lcs.add(cse);
}
for ( JsonOperations tUser : lcs)
{
System.out.println(tUser);
}
my json operation class is
public class JsonOperations {
String match_id, pool_name, team1_name, team1_image, team2_name,
team2_image, match_date, match_country, match_venue, predicted;
public JsonOperations() {
}
public JsonOperations(String match_id, String pool_name, String team1_name,
String team1_image, String team2_name, String team2_image,
String match_date, String match_country, String match_venue,
String predicted) {
this.match_id = match_id;
this.pool_name = pool_name;
this.team1_name = team1_name;
this.team1_image = team1_image;
this.team2_name = team2_name;
this.team2_image = team2_image;
this.match_date = match_date;
this.match_country = match_country;
this.match_venue = match_venue;
this.predicted = predicted;
}
public void set_team1(String team1_name) {
this.team1_name = team1_name;
}
public void set_team2(String team2_name) {
this.team2_name = team2_name;
}
public String get_team1() {
return team1_name;
}
public String get_team2() {
return team2_name;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return this.get_team1() + this.get_team2();
}
}

Converting Java objects to JSON with Jackson

I want my JSON to look like this:
{
"information": [{
"timestamp": "xxxx",
"feature": "xxxx",
"ean": 1234,
"data": "xxxx"
}, {
"timestamp": "yyy",
"feature": "yyy",
"ean": 12345,
"data": "yyy"
}]
}
Code so far:
import java.util.List;
public class ValueData {
private List<ValueItems> information;
public ValueData(){
}
public List<ValueItems> getInformation() {
return information;
}
public void setInformation(List<ValueItems> information) {
this.information = information;
}
#Override
public String toString() {
return String.format("{information:%s}", information);
}
}
and
public class ValueItems {
private String timestamp;
private String feature;
private int ean;
private String data;
public ValueItems(){
}
public ValueItems(String timestamp, String feature, int ean, String data){
this.timestamp = timestamp;
this.feature = feature;
this.ean = ean;
this.data = data;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public int getEan() {
return ean;
}
public void setEan(int ean) {
this.ean = ean;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
}
}
I just missing the part how I can convert the Java object to JSON with Jackson:
public static void main(String[] args) {
// CONVERT THE JAVA OBJECT TO JSON HERE
System.out.println(json);
}
My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?
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);
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 = "sampleU#example.com";
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":"sampleU#example.com"}
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
This might be useful:
objectMapper.writeValue(new File("c:\\employee.json"), employee);
// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
You can use Google Gson like this
UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:
StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
Note: To make the most voted solution work, attributes in the POJO have to be public or have a public getter/setter:
By default, Jackson 2 will only work with fields that are either
public, or have a public getter method – serializing an entity that
has all fields private or package private will fail.
Not tested yet, but I believe that this rule also applies for other JSON libs like google Gson.
public class JSONConvector {
public static String toJSON(Object object) throws JSONException, IllegalAccessException {
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static String toJSON(List list ) throws JSONException, IllegalAccessException {
JSONArray jsonArray = new JSONArray();
for (Object i : list) {
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);
}
return jsonArray.toString();
}
}

Categories

Resources