0

How to convert scala immutable map to JSON using Java?

I have the following example

scala.collection.immutable.Map<java.lang.String, java.lang.Object> statesMap = scala.collection.immutable.Map("AL" -> "Alabama", "AK" -> "Alaska")

and I need to convert this to JSON using Java.

1 Answer 1

0

I'd recommend use Google Gson library for it:

In that case, type the following:

Gson gson = new GsonBuilder().serializeNulls().create();
String convertedMap = gson.toJson(statesMap).toString();
Sign up to request clarification or add additional context in comments.

4 Comments

is .toString() necessary since gson.toJson returns a string ?
No. Just thinking for printing and testing it
for some reason it didn't quite work with two lines you posted
Well, I should work for any Object, but maybe I've underestimate Scala. If is inmutable... is it really neccesary scala Object? You can just create ImmutableMap<String, String> using Google guava library. That works for sure

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.