This is My JSON String : "{'userName' : 'Bachooo'}"
Converting JSON String to LoginVO logic is:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
LoginVO loginFrom = gson.fromJson(jsonInString, LoginVO.class);
System.out.println("userName " + loginFrom.getUserName()); // output null
My LoginVO.class is:
public class LoginVO {
private String userName;
private String password;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
Note I am using jdk 1.8.0_92
Output of loginForm.getUserName() is NULL instead of "Bachooo" any idea about this issue?
Since you are setting excludeFieldsWithoutExposeAnnotation() configuration on the GsonBuilder you must put #Expose annotation on those fields you want to serialize/deserialize.
So in order for excludeFieldsWithoutExposeAnnotation() to serialize/deserialize your fields you must add that annotation:
#Expose
private String userName;
#Expose
private String password;
Or, you could remove excludeFieldsWithoutExposeAnnotation() from the GsonBuilder.
Adding what resolved this for me.
So in my API following gson implementation was getting used:
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
I had to use the same implementation in my test, before which gson was failing to parse attributes.
So in essence check how your gson is configured in api/handler, and use same configuration in your test.
Try like this, please. Here is the example class:
class AngilinaJoile {
private String name;
// setter
// getter
}
And here is how you deserialize it with Gson:
Gson gson = new Gson();
String jsonInString = "{'name' : 'kumaresan perumal'}";
AngilinaJoile angel = gson.fromJson(jsonInString, AngilinaJoile.class);
Related
How can I separate CustomerName and CustomerPhone from this string which I am receiving from API:
{
"CustomerPhone":"0300",
"CustomerName":"Saleh",
"CustomerPassword":"84CYmCulToJXo5KncGwSZa81acb2vbHjZ2IgUveMyeU=",
"Salt":"Q/IoQURM1Cv05wbkJjuo3w=="
}
Below are the very easy steps to get it done,
Step 1: Go to http://www.jsonschema2pojo.org/ and paste your JSON, now select options Target language as Java, Source Type JSON , Annotation Style GSON. And press preview button, and copy model to clipboard.
Step 2: Now in your project Add GSON library
Step 3: Create Model Class with name CustomerData or anything you want, and paste code from clipboard.
It will look alike
public class CustomerData {
#SerializedName("CustomerPhone")
#Expose
private String customerPhone;
#SerializedName("CustomerName")
#Expose
private String customerName;
#SerializedName("CustomerPassword")
#Expose
private String customerPassword;
#SerializedName("Salt")
#Expose
private String salt;
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerPassword() {
return customerPassword;
}
public void setCustomerPassword(String customerPassword) {
this.customerPassword = customerPassword;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Step 4:
Now you have to parse your JSON to GSON Object by following code, where response variable will be your JSON string.
CustomerData customerData = new Gson().fromJson(response,CustomerData.class);
customerData.getCustomerName();
customerData.getCustomerPhone();
Try this:
String jsonText = "{\"CustomerPhone\":\"0300\",\"CustomerName\":\"Saleh\",\"CustomerPassword\":\"84CYmCulToJXo5KncGwSZa81acb2vbHjZ2IgUveMyeU=\",\"Salt\":\"Q/IoQURM1Cv05wbkJjuo3w==\"}";
try {
JSONObject jsonObj = new JSONObject(jsonText);
String CustomerPhone = jsonObj.getString("CustomerPhone");
String CustomerName = jsonObj.getString("CustomerName");
} catch (JSONException e){
e.printStackTrace();
}
You have a few options.
Use a simple JSON library like GSON and create a model that you simply convert the string into and you're done
Use the Android JsonElements and create a JsonElement from the string and walk each child by name until you get the ones you need.
Ugliest way but you can do it, parse the string by known strings. (not tested, you would have to tweak this, but I really hope you don't go this route lol)
var customerStartPhoneIndex = jsonString.indexOf("CustomerPhone\":\")
var customerStartNameIndex = jsonString.indexOf("CustomerName\":\")
var customerEndphoneIndex = jsonString.indexOf(",")
var customerEndNameIndex = jsonString.indexOf(",", str.indexOf(",") +
1)
var customerPhone = jsonString.subString(customerStartPhoneIndex,
customerEndPhoneIndex)
var customerName = jsonString.substring(customerStartNameIndex,
customerEndNameIndex)
For your given String the below code will work fine, I have tested and it is pretty self explaining.
val jsonObject = JSONObject(jsonString)
val phone = jsonObject.getString("CustomerPhone")
val name = jsonObject.getString("CustomerName")
val password = jsonObject.getString("CustomerPassword")
val salt = jsonObject.getString("Salt")
Log.d("phone", phone)
Log.d("name", name)
Log.d("password", password)
Log.d("salt", salt)
Hope this helps thank You
If I try to deserialize a JSON string that is missing a field from the object class, that field is set to null when the object is created. I need Jackson to throw an exception when this happens so I don't have to implement an assertNotNullFields() method in every object; i.e the JSON string input must have defined all the fields in the class or a JsonProcessingException is thrown.
Object mapper configuration:
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
JSON object:
public class LogInUser {
public String identifier, password;
public LogInUser() {}
}
Is this possible given my configuration?
You could try using JsonCreator within your LogInUser class as mentioned here. When introduced into the code you posed in your quesion, it would look something like this:
public class LogInUser {
#JsonCreator
public LogInUser(#JsonProperty(value = "identifier", required = true) String identifier, #JsonProperty(value = "password", required = true) String password) {
this.identifier = identifier;
this.password = password;
}
public String identifier, password;
public LogInUser() {}
}
When one or more of the values are null, it should throw an exception.
I have been applying my expert level googling skills to no avail, so Stackoverflow I need your assistance.
I want to convert my json object to a java object in java.
JSON object appears as...
- {"password":"b","userName":"a"}
and the print statements once i 'attempt' to convert it are...
username = b
password = null
my question is why is this happening and how can i solve the issue? (Code follows)
Gson gson = new Gson();
JSONObject jObj = new JSONObject(request.getParameter("input"));
User user = gson.fromJson(jObj.toString(), User.class);
System.out.println(user.getPassword());
System.out.println(user.getUsername());
and the 'model' class....
public class User {
private String username;
private String password;
public User(String uName, String pWord){
this.username = uName;
this.password = pWord;
}
public void setUsername(String uName){
username = uName;
}
public String getUsername(){
return username;
}
public void setPassword(String pWord){
password = pWord;
}
public String getPassword(){
return password;
}
}
The solution in this case was was related to the mapping in the JSON as 'userName' when it should have been 'username'
refer to the comments for additional information.
hopefully other users find this a useful resource.
I am looking for best solution how to convert POJO or JSON to XML with all atttributes in correct places. For now, Jackson looks like the most convenient way. I am able to serialize POJO to XML without attributes.
POJO TestUser
public class TestUser extends JsonType
{
#JsonProperty("username")
private final String username;
#JsonProperty("fullname")
private final String fullname;
#JsonProperty("email")
private final String email;
#JsonProperty("enabled")
private final Boolean enabled;
#JsonCreator
public TestUser(
#JsonProperty("username") String username,
#JsonProperty("fullname") String fullname,
#JsonProperty("email") String email,
#JsonProperty("enabled") Boolean enabled)
{
this.username = username;
this.fullname = fullname;
this.email = email;
this.enabled = enabled;
}
#JsonGetter("username")
public String getUsername()
{
return username;
}
#JsonGetter("fullname")
public String getFullname()
{
return fullname;
}
#JsonGetter("email")
public String getEmail()
{
return email;
}
#JsonGetter("enabled")
public Boolean getEnabled()
{
return enabled;
}
}
}
Here is the code:
public void testJsonToXML() throws JsonParseException, JsonMappingException, IOException
{
String jsonInput = "{\"username\":\"FOO\",\"fullname\":\"FOO BAR\", \"email\":\"foobar#foobar.com\", \"enabled\":\"true\"}";
ObjectMapper jsonMapper = new ObjectMapper();
TestUser foo = jsonMapper.readValue(jsonInput, TestUser.class);
XmlMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.writer().with(SerializationFeature.WRAP_ROOT_VALUE).withRootName("product").writeValueAsString(foo));
}
And now it returns this
<TestUser xmlns="">
<product>
<username>FOO</username>
<fullname>FOO BAR</fullname>
<email>foobar#foobar.com</email>
<enabled>true</enabled>
</product>
</TestUser>
Which is nice, but I need variable enabled to be attribute of username and then I need to add xmlns and xsi attributes to the root element so the XML result looks like this
<TestUser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="testUser.xsd">
<product>
<username enabled="true">FOO</username>
<fullname>FOO BAR</fullname>
<email>foobar#foobar.com</email>
</product>
</TestUser>
I found some examples using #JacksonXmlProperty but it only adds the attribute to the root element.
Thanks for help
Interesting problem: injection of additional data. There is no functionality for doing that currently; but I think it'd be possible to add, say, a new attribute in #JsonRootName (schema=URL?), that would allow addition of a schema mapping or mappings?
I went ahead and filed this:
https://github.com/FasterXML/jackson-dataformat-xml/issues/90
to add something that should work; feel free to add comments, suggestions.
What design-pattern, if any, would be most appropriate in this situation.
public class PersonFromDB1 {
private String firstName;
private String lastName;
private String Car;
}
public class PersonFromDB2 {
private String first_name;
private String last_name;
private String boat;
}
Out of these two person types, the only data I would like to work on is fist name and last name regardless of how it field name is name inside the different DBs. firstName and first_name represents the same - name of a person/customer - so does lastName and last-name. The car and boat fields are, in my example, completely irrelevant and should therefore be ignored.
Using, maybe polymorphism or the adapter pattern (?), I would like to create a list of objects that includes persons from DB1 and DB2 under the same type - of PersonInOurDB.
In the end, my goal is to be able to call GSON serialization/desarialization on myClass alone.
public class PersonInOurDB {
private String firstname;
private String lastname;
}
A simple selection based on the type is all you really need. This could be considered a builder pattern because it just initializes a new instance of myClass.
Note, this is rough pseudo code.
FunctionName(SomeType instance)
{
string aPostfix = "_1";
string bPostfix = "_2";
string selectedPostFix;
// This is your strategy selector
switch(typeof(SomeType.Name)
{
case "TypeA":
selectedPostFix = aPostFix;
case "TypeB":
selectedPostFix = bPostFix;
}
return new myClass()
{
A = instance.GetProperty("A" + selectedPostfix).Value,
B = instance.GetProperty("B" + selectedPostfix).Value,
...
}
}
If you want a common access api in java for both objects, then introduce an interface and let both implement it.
If you only want both objects (PersonFromDB1 and PersonFromDB2) to be serialized in the same way by json you can either:
use annotations - the #SerializedName annotation in combination with #Expose.
use the FieldNamingStratgy and ExclusionStrategy
Use annotations to control the serialization
public class PersonFromDB1 {
#Expose
#SerializedName("firstName")
private String firstName;
#Expose
#SerializedName("lastName")
private String lastName;
private String car;
}
public class PersonFromDB2 {
#Expose
#SerializedName("firstName")
private String first_Name;
#Expose
#SerializedName("lastName")
private String last_Name;
private String boat;
}
Then you can use the GsonBuilder
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
PersonFromDB1 person1 = ...; // get the object
PersonFromDB2 person2 = ...; // get the object
System.out.println(gson.toJson(person1));
System.out.println(gson.toJson(person2));
Use FieldNamingStratgy and ExclusionStrategy to control the serialization
If you don't want to modify the db objects (you can't or you don't want to add annotations) than there is another way. You can use a FieldNamingStratgy and ExclusionStrategy.
class PersonFromDBNamingStrategy implements FieldNamingStrategy {
Map<String, String> fieldMapping = new HashMap<String, String>();
public PersonFromDBNamingStrategy() {
fieldMapping.put("first_Name", "firstName");
fieldMapping.put("last_Name", "lastName");
}
#Override
public String translateName(Field f) {
String name = f.getName();
if(fieldMapping.contains(name)){
return fieldMapping.get(name);
}
return name;
}
}
and the ExclusionStrategy
class PersonFromDExclusionStrategy implements ExclusionStrategy {
List<String> validNames = Arrays.asList("car", "boat");
#Override
public boolean shouldSkipField(FieldAttributes f) {
String name = f.getName();
return !validNames.contains(name);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
after that just create Gson like this:
GsonBuilder gsonBuilder = new GsonBuilder();
sonBuilder.addSerializationExclusionStrategy(new PersonFromDExclusionStrategy());
gsonBuilder.setFieldNamingStrategy(new PersonFromDBNamingStrategy());
Gson gson = gsonBuilder.create();
PersonFromDB1 person1 = ...; // get the object
PersonFromDB2 person2 = ...; // get the object
System.out.println(gson.toJson(person1));
System.out.println(gson.toJson(person2));