I have an interesting problem to solve.
Let's consider the following classes ( Person and Telephone ):
Person
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Person {
private String name;
private int age;
private Telephone telephone;
}
Telephone
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Telephone {
private int codeArea;
private String number;
}
And suppose that I have a Person object string generated by the lombok annotation @ToString :
Person(name=John, age=30, telephone=Telephone(codeArea=16, number=1111-2222))
How can I convert the string above to the object again? Is there any library that can help me with this process, or do I have to create manually a parser for it?
I know that there are other ways like generating json or serializing as a java object and then converting it back. However, this is not a solution for me now, as I must have to work with the string mentioned above.
Instead, do this in the class.
/**
* Object as JSON string.
* @return
*/
public String toString() {
// Initiate GSON = new GsonBuilder().create();
return GSON.toJson(this);
}
From Object to String : object.toString().
From String to Object : GSON.fromJson(jsonString, ModelClass);
Finally, I came up with the idea of converting this string into JSON format and then convert it to the object.
So, the string generated by lombok is:
Person(name=John, age=30, telephone=Telephone(codeArea=16, number=1111-2222))
And then it is converted to JSON, by replacing the following characters ( , = and ) with { , : and } respectively, and removing the class names:
{name:John, age:30, telephone:{codeArea=16, number=1111-2222}}
Now it is possible to convert the JSON into an object.
I created a project in Github that does this conversion.
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.