1

I have json string like this:

str = {"id" : %s, "name": %s}

I want to replace format specifier %s with values. I have array that contains values to be replaced.

I am able to do this using

str.format(arrayofvalue: _*)  

but this works only for one specific type format identifier.

what in case if i have string with multiple format specifier like (%d, %s)

str = {"id" : %d, "name": %s}

above solution does not work in this case (illegalFormatConversion). Is there any function/ work around to handle this.

3
  • 1
    Could you post the whole exception message? Commented May 5, 2016 at 10:38
  • java.util.IllegalFormatConversionException: d != java.lang.String Commented May 5, 2016 at 10:42
  • See the answers, if you still have trouble, you should also post how you initialize arrayofvalue. Commented May 5, 2016 at 11:03

2 Answers 2

1

Using str.format(arrayofvalue: _*) works. Your problem is that you pass in the incorrect type in your array, or have the order of values in the array wrong.

You can verify it works with this example:

val str = """{"id" : %d, "name": %s}"""
val arrayOfValue = Array(1, "John")
str.format(arrayOfValue: _*) // returns: {"id" : 1, "name": John}

Now if I changed arrayOfValue to

val arrayOfValue = Array("1", "John") 

(notice that argument "1" is now not an Int but a String), you get the exception java.util.IllegalFormatConversionException: d != java.lang.String.

Sign up to request clarification or add additional context in comments.

Comments

1

you get this exception if the types are not compatible.

 val str = "{\"id\" : %d, \"name\": %s}"
 val arrayofvalue = Array("1", "a")
 val output = str.format(arrayofvalue: _*)
 println(output)    
 // will result in java.util.IllegalFormatConversionException: d != java.lang.String

But if you provide compatible types it will work:

 val str = "{\"id\" : %d, \"name\": %s}"
 val arrayofvalue = Array(1, "a")
 val output = str.format(arrayofvalue: _*)
 println(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.