1

I'd like to have a JSON formatted String in the buildConfig but the build process messes the string up and I'm not sure how to fix it.

This is the JSON:

{
    "testkey1": "someValue1",
    "testkey2": 3,
    "testkey3": {
        "innerKey1": "innerValue1",
        "innerKey2": "innerValue2"
    }
}

In my gradle file I have the following (Android Studio adds escapes)

buildConfigField "String", "JSON", "\"{\"testkey1\": \"someValue1\",\"testkey2\": 3,\"testkey3\": {\"innerKey1\": \"innerValue1\",\"innerKey2\": \"innerValue2\"}}\""

What it compiles (auto-generates) from the above is

public static final String JSON = "{"testkey1": "someValue1","testkey2": 3,"testkey3": {"innerKey1": "innerValue1","innerKey2": "innerValue2"}}";

The problem is that all the escapes are missing in the generated code. This is not a valid String. It should be more like this

public static final String JSON = "{\"testkey1\": \"someValue1\",\"testkey2\": 3,\"testkey3\": {\"innerKey1\": \"innerValue1\",\"innerKey2\": \"innerValue2\"}}";

But how?

Emanuel
  • 863
  • 9
  • 29
  • 2
    `\"` => `\\\"` ? now you are only escaping them for gradle ... off-topic comment: use file resource instead buildConfig – Selvin Jul 19 '19 at 08:57
  • try beginning and ending the entire string with `'` instead of `\"`. But using a file resource name is better solution, as Selvin mentioned – Vladyslav Matviienko Jul 19 '19 at 09:02
  • can you drop me a link to some info about file resources? – Emanuel Jul 19 '19 at 09:07
  • just put a text files into assets, each of which contains different variants of JSON you need for different builds. In `buildConfigField` put the names of those files instead. And wherever you need to use that JSON - load it from the file by the name in `BuildConfig` – Vladyslav Matviienko Jul 19 '19 at 09:09

0 Answers0