This has been a solved problem for at least two decades. Use ASN.1 and choose your encoding rules accordingly: JER when you need JSON, XER when you need XML, and switch to BER/DER when you need to reduce transfer costs.