Unwanted "_0" name in JSON

The following snippet:

struct Foo: Codable {
    var x: Int
    var y: String
}

enum E: Codable {
    case foo(Foo)
    case bar(Bar)
}

let v = E.foo(.init(x: 1, y: "2"))
let enc = JSONEncoder()
enc.outputFormatting = .prettyPrinted
let s = String(data: try! enc.encode(v), encoding: .utf8)!
print(s)

Outputs:

{
  "foo" : {
    "_0" : {
      "x" : 1,
      "y" : "2"
    }
  }
}

Is there a way to rename "_0" to something less horrible? Or even remove this extra level? Ideally without implementing encode/decode myself! (which will result into unwanted amount of boilerplate). I am flexible on the types themselves (e.g. can change enum to something else, etc).

I would consider:

struct E {
    var foo: Foo?
    var bar: Bar?
}

which is less ideal as I will have to ensure that there's one and only one non-nil option to keep the desired "enum" semantics.

If you use labels for your associated values, they are used:

enum E: Codable {
    case foo(value: Foo)
    // ...
}

outputs:

{
  "foo" : {
    "value" : {
      "x" : 1,
      "y" : "2"
    }
  }
}
2 Likes

CodingKeys approach would allow me to rename either "x" / "y" or "foo" in this JSON (depending upon where I put it):

{
  "foo" : {
    "_0" : {
      "x" : 1,
      "y" : "2"
    }
  }
}

As for renaming "_0"@sveinhal answer is correct.