Jackson - how to send byte value as char in json sting - java

I want to deserialize this json string
{"value":"Y"}
to this object
public class Data {
byte value;
public byte getValue() {
return value;
}
public void setValue(byte value) {
this.value = value;
}
}
ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(js, Data.class);
it works when in json string I put an ascii code
{"value":89}
But I want to use char value.
Main problem is that Data class is legacy class, and I can't add #JsonDeserialize annotation inside it.
Any other option?

Related

Get a value list of a enum to a json object

I want to create a json object with values of "3D Tour", "Videos", "Photos Only", etc. You can find the enum class below. How can I implement that?
package com.padgea.listing.application.dto;
public enum General implements Catalogue {
Tour("3D Tour"),
Videos("Videos"),
Photos_Only("Photos Only"),
Price_Reduced("Price Reduced"),
Furnished("Furnished"),
Luxury("Luxury");
private final String value;
General(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
I need a output like this
{General : "3D Tour","Videos","Photos Only",etc}
This will return a list of strings containing all the values.
enum General implements Catalogue {
Tour("3D Tour"),
Videos("Videos"),
Photos_Only("Photos Only"),
Price_Reduced("Price Reduced"),
Furnished("Furnished"),
Luxury("Luxury");
private final String value;
General(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static List<String> valuesList() {
return Arrays.stream(General.values())
.map(General::getValue)
.collect(Collectors.toList());
}
}
And a level up you'll do something like
myJson.put("General", General.valuesList())
An output will be
{
"General": ["3D Tour","Videos","Photos Only"]
}
The valid JSON would look like this
{
"General": ["3D Tour","Videos","Photos Only"]
}
If you would use Jackson library for creating your JSON you would need to create a class like this:
public class GeneralDTO {
#JsonProperty("General")
private String[] general;
...
}
Then you would need to create your GeneralDTO object.
You can get all your enum values in an array like this
String[] generalArray = Arrays.stream(General.values())
.map(st -> st.getValue())
.toArray(String[]::new);
Then using the method writeValueAsString of ObjectMapper class (part of Jackson library) you can get JSON string from your GeneralDTO object.
To simplify you can use Map<String, String[]> instead of GeneralDTO
Map<String, String[]> generalObject = new HashMap<>;
generalObject.put("General", generalArray);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(generalObject);

Convert NaN value into null when parsing json using jackson library

What is the best way to parse a json string in to a JsonNode object, and convert all the NaN value in to null ? The following code will convert the Nan to DoubleNode NaN. I try to register a custom deserializer but it didn't pick up the Nan node.
JsonMapper mapper = JsonMapper.builder()
.enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS).build();
final String testJson = "{\"key\":NaN}";
JsonNode node = mapper.readTree(testJson)
One way it could be done is like below
Create some POJO class with #JsonSetter on setter method.
public class KeyPojo {
private Double key;
#JsonSetter
public void setKey(Double key) {
if (Double.isNaN(key)) {
this.key = null;
} else {
this.key = key;
}
}
}
And parse json text like below.
KeyPojo keyObj = mapper.readValue(testJson, KeyPojo.class);
now, keyObj.key contains NULL value.

Java object to JSON with only selected fields

I have java class like:
public class Sample{
int foo=5;
int bar=6;
}
now I want to generate JSON object but without bar field:
{"foo":5}
What is a best way to accomplish that?
Should I compose JSON string manually, or can I use some library, or generator?
Should I compose JSON string manually
Avoid this, it's all to easy to make invalid json this way. Use of a library ensures proper escaping of characters that would otherwise break the output.
Gson ignores transient fields:
public class Sample {
private int foo = 5;
private int transient bar = 6;
}
Gson gson = new Gson();
Or you can choose which to include with Expose attribute:
public class Sample {
#Expose private int foo = 5;
private int bar = 6;
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Then whichever approach, do this:
String json = gson.toJson(obj);
To get your desired {"foo":5}
You can use the Jackson to solve your problem. Follow the below step -
Step 1 - Make a method which will convert Java object to Json
public class JsonUtils {
public static String javaToJson(Object o) {
String jsonString = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);
jsonString = objectMapper.writeValueAsString(o);
} catch (JsonGenerationException e) {
logger.error(e);
} catch (JsonMappingException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return jsonString;
}
}
Step 2 Model Class
package com.javamad.model;
import org.codehaus.jackson.annotate.JsonIgnore;
public class Sample{
int foo=5;
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
#JsonIgnore
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
int bar=6;
}
Step 3 Convert your java class to json
Sample sample = new Sample()
JsonUtils.javaToJson(sample);
you can try Gson, JSON library, to convert object to/from json.
these two methods are helpfull:
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

how can I deserialize a non unified json in Java?

I want to send the server an http request with this json (upper line)
and I want to get such a json and parse it to Java object (lower line)
I remember from last times, that a missing field in a collection that I want to deserialize
crashes the deserialization
(for a single deserialization, if the json has no such field - a default value is inserted)
Is there any way I can create a single Java class to represent both the request json and the two types on response json objects?
My try:
public class ConfigValue {
public String key;
public String defaultValue;
public String value;
}
Gson gson = new Gson();
Type collectionType = new TypeToken<Array<ConfigValue>>() {
}.getType();
ConfigValue[] configValues = (ConfigValue[]) gson
.fromJson(result, collectionType);
Neither of the two JSON strings in your image are directly a list (or array) of ConfigValue objects. They are in fact a JSON object, with one property configValues, which is a list of ConfigValue objects. You therefore need a wrapper class to deserialize them to:
public class ConfigValues {
public ConfigValue[] configValues;
}
public class ConfigValue {
public String key;
public String defaultValue;
public String value;
}
public static void main(String[] args) {
String firstJson = "{\"configValues\":[{\"key\":\"radiusMeters\",\"value\":\"200\"}]}";
String secondJson = "{\"configValues\":[{\"key\":\"redeemExpirationMins\",\"defaultValue\":\"300\"},{\"key\":\"radiusMeters\",\"value\":\"200\",\"defaultValue\":\"400\"}]}";
Gson gson = new Gson();
ConfigValues firstConfigValues = gson.fromJson(firstJson, ConfigValues.class);
ConfigValues secondConfigValues = gson.fromJson(secondJson, ConfigValues.class);
System.out.println(firstConfigValues);
System.out.println(secondConfigValues);
}
If you add toString methods to the two classes, the main method prints the following deserialized objects:
ConfigValues(configValues=[ConfigValue(key=radiusMeters, defaultValue=null, value=200)])
ConfigValues(configValues=[ConfigValue(key=redeemExpirationMins, defaultValue=300, value=null), ConfigValue(key=radiusMeters, defaultValue=400, value=200)])
You can see that any missing fields of ConfigValue are deserialized to null.

How to parse json data using in java

I am getting this data from server how to parse this data in java .
LabelField jsonResult = new LabelField(connectJson.response);
"[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]"
I am getting response in jsonResult variable
You can use libraries like Jackson to do the same. There is also Google's GSON which will help you do the same. See this example
Take a look at the JSONParser Object in this Tutorial
If you are using Eclipse plugin than may JSON library included in you SDK.
Use below code to parse your JSON string got from the server.
String test = "[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]";
JSONArray array = new JSONArray(test);
JSONObject obj = (JSONObject) array.get(0);
Your String look like you got JSON Array from the server.
First convert your Json string to JSON Array by
JSONArray array = new JSONArray(Your JSON String);
Each element in array represent JSON Object.You can read JSON Object by
JSONObject obj = (JSONObject) array.get(Index);
You can read parameter from Object to any String variable by :
String valueStr = obj.getString("screen_refresh_interval");
May this help you.
Design a class (viz CustomClass) first with screen_refresh_interval and station_list_last_update as properties. And Make a collection class for CustomClass
I'm using Gson as deserializer. Other libraries are also available.
public class Container {
private CustomClass[] classes;
public CustomClass[] getClasses() {
return classes;
}
public void setClasses(CustomClass[] classes) {
this.classes = classes;
}
}
public class CustomClass {
private String screen_refresh_interval;
private String station_list_last_update;
public String getScreen_refresh_interval() {
return screen_refresh_interval;
}
public void setScreen_refresh_interval(String screen_refresh_interval) {
this.screen_refresh_interval = screen_refresh_interval;
}
public String getStation_list_last_update() {
return station_list_last_update;
}
public void setStation_list_last_update(String station_list_last_update) {
this.station_list_last_update = station_list_last_update;
}
}
Gson gson = new Gson();
Container customClassCollection = gson.fromJson(jsonResult, Container.class);

Categories