how to avoid jackson escaping backslash? - java

I set "this\'s my case!" to an object's field.
Calling writeAsString, output is "this\\\'s my case!".
But I expect "this\'s my case!".
How can I get what I want ?
public class CommonUtils {
public static ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getObjectMapperInstance(){
return objectMapper;
}
public static void main(String[] args) throws IOException {
CommonUtils commonUtils = new CommonUtils();
commonUtils.test();
}
public void test() throws IOException {
List<MyObject> list = new ArrayList<MyObject>();
String xx = "page://list?params={\"city\"}";
list.add(new MyObject(1,xx));
}
class MyObject{
public MyObject(int tag,String str){
this.tag = tag;
this.str = str;
}
int tag;
String str;
public int getTag() {
return tag;
}
public void setTag(int tag) {
this.tag = tag;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
}
Output of above code:
[ {
"tag" : 1,
"str" : "page://list?params={\\"city\\"}]
What I want is:
[ {
"tag" : 1,
"str" : "page://list?params={\"city\"}]

If you Change the String xx to
String xx = "page://list?params={\\\"city\\\"}"; //page://list?params={\"city\"}
You will get desired result;
[ { "tag" : 1, "str" : "page://list?params={\"city\"}]

Related

Java send class parameters by only one object

It is possible to create an Object as "only for parameters"?. For example:
class MyClass {
public String a;
public Number b;
public MyClass(Object params) {
this.a = params.a !== null ? params.a : "default";
this.b = params.b !== null ? params.b : 0;
}
}
void main() {
MyClass myclass1 = new MyClass(new Object() {
String a = "hey";
});
MyClass myclass2 = new MyClass(new Object() {
Number b = 123;
});
MyClass myclass3 = new MyClass(new Object() {
String a = "!!!";
Number b = 5;
});
}
Obviously this code doesn't work, I tried a lot of ways trying to replicate it, maybe with Templates (Generic)?
The expected results will be:
myclass1.a == "hey";
myclass1.b == 0;
myclass2.a == "default";
myclass2.b == 123;
myclass3.a == "!!!";
myclass3.b == 5;
You could use a Builder pattern to create required instance:
public final class MyClass {
private final String str;
private final Number number;
public static Builder builder() {
return new Builder();
}
private MyClass(Builder builder) {
str = builder.str;
number = builder.number;
}
public String getStr() {
return str;
}
public Number getNumber() {
return number;
}
public static final class Builder {
private String str = "default";
private Number number = 0;
private Builder() {
}
public MyClass build() {
return new MyClass(this);
}
public Builder str(String str) {
this.str = str;
return this;
}
public Builder number(Number number) {
this.number = number;
return this;
}
}
}
Demo:
public static void main(String... args) {
MyClass myclass1 = MyClass.builder().str("hey").build();
MyClass myclass2 = MyClass.builder().number(123).build();
MyClass myclass3 = MyClass.builder().str("!!!").number(5).build();
}
In case you do not want to use Builder pattern, you could use class override:
public class MyClass {
public String getStr() {
return "default";
}
public Number getNumber() {
return 0;
}
}
public static void main(String... args) throws IOException {
MyClass myclass1 = new MyClass() {
#Override
public String getStr() {
return "hey";
}
};
MyClass myclass2 = new MyClass() {
#Override
public String getStr() {
return "hey";
}
#Override
public Number getNumber() {
return 123;
}
};
MyClass myclass3 = new MyClass() {
#Override
public String getStr() {
return "!!!";
}
#Override
public Number getNumber() {
return 5;
}
};
}

Jackson deserialize an array of object to pojo

So i have this JSON file
{
"results":[
"result":{},
"result":{}
]
}
I wish to deserialize it to a java object which contains an array of result objects.
public class Foo(){
#JsonProperty("results")
private Result[] results;
public void setResults(Result[] results){
this.results = results;
}
public Result[] getResults(){
return this.results;
}
}
public class JsonToObject(){
ObjectMapper mp = new ObjectMapper();
public void createObject(String jsonFile){
Foo bar = mp.readValue(jsonFile, Foo.Class)
}
}
My issue is I keep getting deserialization issues as I have not definied "result".
One way I can get around this is to have result as a class variable inside Result but that seems stupid to do and also may cause issues with re-serializing.
How can I convert the JSON so that my class contains an array of result?
Your question program is wrong. There are many problems with your code. Please use below sample:
public class Foo {
#JsonProperty("results")
private Result[] results;
public Foo() {
}
public Result[] getResults() {
return results;
}
public void setResults(Result[] results) {
this.results = results;
}
}
public class Result {
private String name;
public Result() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mp = new ObjectMapper();
String content = "{\"results\":[{\"name\":\"apple\"},{\"name\":\"lemon\"}]}";
Foo bar = mp.readValue(content, Foo.class);
}

Jackson : map nested object

Using jackson, i wonder if it's possible du map json to Java with nested Object that are not like the json structure.
Here an exemple of what i want to do.
Json :
{
a = "someValue",
b = "someValue",
c = "someValue"
}
Java :
public class AnObject {
#JsonProperty("a")
private String value;
//Nested object
private SomeObject;
}
public class SomeObject {
#JsonProperty("b")
private String value1;
#JsonProperry("c")
private String value2;
}
Is it possible ?
Use the JsonUnwrapped annotation:
#JsonUnwrapped
private final SomeObject someObject;
which unwrappes all of SomeObject's fields into the parent, resulting in the following when serializing:
{"a":"foo","b":"bar","c":"baz"}
Using ObjectMapper you can convert JSON string to Object.
Use JsonUnwrapped in your AnObject class over someObject field.
#JsonUnwrapped
private SomeObject someObject;
then read JSON string and convert it to AnObject.
ObjectMapper mapper = new ObjectMapper();
try {
AnObject anObject1 = mapper.readValue(jsonString, AnObject.class);
} catch (IOException e) {
e.printStackTrace();
}
First of all, this is a JSON object.
It's an object literal.
Second of all, that is not a valid formatted object literal.
The correct one is this:
{ "a" : "someValue", "b": "someValue", "c": "someValue"}
Next, as sayd in comments, you have to define your own deserializer.
Main:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"a\" : \"someValue\",\"b\" : \"someValue\",\"c\" : \"someValue\"}";
final ObjectMapper om =
new ObjectMapper();//
om.registerSubtypes(AnObject.class);
SimpleModule module = new SimpleModule();
module.addDeserializer(AnObject.class, new CustomDeserializer2());
om.registerModule(module);
AnObject ob = om.readValue(json, AnObject.class);
System.out.println(ob.getValue());
System.out.println(ob.getObject().getValue1());
System.out.println(ob.getObject().getValue2());
}
Deserializer:
public class CustomDeserializer2 extends StdDeserializer<AnObject> {
private static final long serialVersionUID = -3483096770025118080L;
public CustomDeserializer2() {
this(null);
}
public CustomDeserializer2(Class<?> vc) {
super(vc);
}
#Override
public AnObject deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode interNode = jp.getCodec().readTree(jp);
AnObject ob = new AnObject();
if (interNode.get("a") != null) {
ob.setValue(interNode.get("a").toString());
}
SomeObject obj = new SomeObject();
if (interNode.get("b") != null) {
obj.setValue1(interNode.get("b").toString());
}
if (interNode.get("c") != null) {
obj.setValue2(interNode.get("c").toString());
}
ob.setObject(obj);
return ob;
}
Model: Pay attention to #JsonProperty on A field
public class AnObject {
#JsonProperty("a")
private String value;
private SomeObject object;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public SomeObject getObject() {
return object;
}
public void setObject(SomeObject arg) {
object = arg;
}
public class SomeObject {
private String value1;
private String value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
Bye

JSON parse with Objectmapper JAVA

This is the JSON string:
{
"d":{
"results":[
{
"__metadata":{
"uri":"http://blabla1",
"type":"type1"
},
"Synonym":"miami"
},
{
"__metadata":{
"uri":"http://blabla2",
"type":"type2"
},
"Synonym":"florida"
}
]
}
}
This is the code:
public class Test{
#JsonIgnoreProperties(ignoreUnknown = true)
public static class d {
public List<Results> results;
public d() {
results = new ArrayList<Results>();
}
public static class Results {
public Metadata __metadata;
public String Synonym;
public Results() {}
}
public static class Metadata {
public String uri;
public String type;
public Metadata() {}
}
}
}
With the following mapper:
ObjectMapper mapper = new ObjectMapper();
Test.d readValue = mapper.readValue(jsonString, Test.d.class);
for (Test.d.Results k : readValue.results) {
System.out.println("synonym: "+k.Synonym);
}
It gives me no error, just an empty arraylist of results...
p.s. i have made a lot of changes in between time, sorry for the inconvenience
you must create an object that fits with the jSon answer, something like this (not tested):
class d {
public List<Results> results;
public d() {
}
}
class Results {
public Metadata metadata;
public String synonym;
public Results() {
}
}
class Metadata {
public String uri;
public String type;
public Metadata() {
}
}
Hope it helps!
I have managed to solve it.
i forgot to make setters and getters for class 'd'.
public class Test {
private d d;
public d getD() {return d;}
public void setD(d d) {this.d = d;}
public static class d{
private List<Results> results;
public List<Results> getResults() {return results;}
public void setResults(List<Results> results) {this.results = results;}
}
public static class Results {
public Metadata __metadata;
public String Synonym;
}
public static class Metadata {
private String uri;
private String type;
public String getUri() {return uri;}
public void setUri(String uri) {this.uri = uri;}
public String getType() {return type;}
public void setType(String type) {this.type = type;}
}
}
This is the map:
Test test = mapper.readValue(json, KeyPhrase.class);
System.out.println("cp");
for(Test.Results res : test.getD().getResults()){
System.out.println(res.Synonym);
}

Using Gson with multiple values for object

I have this Json code:
{
"term" : {
"PrincipalTranslations" : {
"0" : {
termine:"casa",
traduzione:"home"
}
"1" :{
termine:"testa",
traduzione:"head"
}
"2" :{
termine:"dito",
traduzione:"finger"
}
}
}
}
How can I deserialize the object 0, 1, 2??
If instead of object 0, 1, 2 I wrote object "zero" (and stop), it works!
I've used this implementation:
public class Item {
private term term;
public term getTERM() {
return term;
}
}
public class term {
private PrincipalTranslations PrincipalTranslations;
public PrincipalTranslations getPrincipalTranslations() {
return PrincipalTranslations;
}
}
public class PrincipalTranslations {
private zero zero;
public zero getZero() {
return zero;
}
}
public class zero {
private String termine;
public String gettermine() {
return termine;
}
}
and use it so, it print (in the right way) "casa"
public class MainClass {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("/home/peppe/test_ff");
Gson gson = new GsonBuilder().create();
Item p = gson.fromJson(reader, Item.class);
System.out.print(p.getTERM().getPrincipalTranslations().getZero().gettermine());
reader.close();
}
}
If you want to call the object zero, than in your ’Principal Translations‘ class use the ’SerializedName’ annotation: http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/annotations/SerializedName.html
It will look like this:
#SerializedName("0")
public Zero zero;

Categories

Resources