smilyface
smilyface

Reputation: 5513

Autowire json value in springboot from yaml

How to read json as a string from a yaml file in spring boot application ?

I need to get the json as a string / json object.

Application.yml

Shirt:
 rest:
  booking:
   invoiceAddress: {"name":"VIA Pics AB","address1":"VIA Pics AB","address2":"Mejerivägen 3","zipCode":"11743","city":"STOCKHOLM","countryCode":"SE","email":"[email protected]"}

Configuration class

@Configuration
public class ConfigurationServiceClientConfiguration {

    @Value("${Shirt.rest.booking.invoiceAddress}")
    private String invoiceAddress;

    @Bean
    public String getInvoiceAddress(){
        System.out.println(invoiceAddress);
        return this.invoiceAddress;
    }
}

Also tried @JsonProperty but no idea whether my usage was wrong or not !

Note: I am not ready to change the json as a list because more jsons (of invoiceAddress) to come and I will have to make list for each. So it's easy for me if the json can be copied as it is to the yaml file.

Upvotes: 5

Views: 10262

Answers (4)

David KELLER
David KELLER

Reputation: 636

Shirt:
 rest:
  booking:
   invoiceAddress: >
    {"name":"VIA Pics AB","address1":"VIA Pics AB","address2":"Mejerivägen 3","zipCode":"11743","city":"STOCKHOLM","countryCode":"SE","email":"[email protected]"}

@see https://stackoverflow.com/a/17093553/2929352

Upvotes: 1

Nilesh Kumar
Nilesh Kumar

Reputation: 199

Single quotes escapes all the special characters in the values of YAML properties. Just try adding to the string into single quotes 'PropertiesValue'.

E.g :

invoiceAddress: '{"name":"VIA Pics AB","address1":"VIA Pics AB","address2":"Mejerivägen 3","zipCode":"11743","city":"STOCKHOLM","countryCode":"SE","email":"[email protected]"}'

Upvotes: 0

Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

If you want as a plan string you should add this value between single quote 'your value.' in your yml file

Shirt:
 rest:
  booking:
   invoiceAddress: '{"name":"VIA Pics AB","address1":"VIA Pics AB","address2":"Mejerivägen 3","zipCode":"11743","city":"STOCKHOLM","countryCode":"SE","email":"[email protected]"}'

Upvotes: 13

Try modifying your yml file as below:

Shirt.rest.booking:
   invoiceAddress: "\"name\":\"VIA Pics AB\",\"address1\":\"VIA Pics AB\",\"address2\":\"Mejerivägen 3\",\"zipCode\":\"11743\",\"city\":\"STOCKHOLM\",\"countryCode\":\"SE\",\"email\":\"[email protected]\""

Upvotes: 0

Related Questions