2

I am trying to read object and convert into string. But the root element is getting changed from payment_token to PaymentToken.

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
String requestString = mapper.writeValueAsString(paymentToken); //paymenttoken is valid object

Input Object:

{
    "payment_token": {
        "client_id": "test",
        "currency_code": "USD" 
    }
}

Getting Output as:

{
    "PaymentToken": {
        "client_id": "test",
        "currency_code": "USD"
    }
}

Help me to get the root object as it is in input ?

Kiran
  • 839
  • 3
  • 15
  • 45
  • Your JSON is broken. Also The paymentToken is unclear. Can you add how you construct paymentToken and if it has a DTO class share that also. – pirho Jan 06 '19 at 16:25

1 Answers1

0

You can use as following

import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "payment_token")
public class PaymentToken {
...
}

Ref: JsonRootName

If you add above annotation, Let see how it works
Add following configuration to ObjectMapper

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); // additional to your config
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
String paymentToken = "{\"payment_token\":{\"client_id\":\"test\",\"currency_code\":\"USD\"}}";

System.out.println(mapper.readValue(paymentToken, PaymentToken.class));
System.out.println(mapper.writeValueAsString(paymentToken));

output:

PaymentToken(clientId=test, currencyCode=USD)
{"String":"{\"payment_token\":{\"client_id\":\"test\",\"currency_code\":\"USD\"}}"}

As you can see above, objectMapper deserialize and serialize properly.

dkb
  • 4,389
  • 4
  • 36
  • 54
  • I don't have access to this class, is there any mapper configuration ? – Kiran Dec 25 '18 at 07:59
  • None of the configurations is required, which Jackson version you are using? add `com.fasterxml.jackson.core:jackson-core:2.4.x` as dependency, version should be >= 2.4.0, I used 2.9.8 version – dkb Dec 25 '18 at 08:04
  • i am using `2.9.6` version. not sure why it is returning root element `PaymentToken`. I can not use annotation in the pojo since i don't have the class. – Kiran Dec 25 '18 at 08:22
  • you mean you do not want "PaymentToken" key in string and wanted only `{"client_id":"test","currency_code":"USD"}` ? – dkb Dec 25 '18 at 09:01
  • my ask is here as mentioned in question `Help me to get the root object as it is in input` – Kiran Dec 25 '18 at 16:52