jsongoxml-to-json

JSON to XML in go lang


Hi I am trying the below code in go lang, where i have to change a json data to xml and pass it to another service. Below is the function that i tried for json to xml conversion

package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
)

type Address struct {
        Address1 string `json:"Address1"`
        Address2  string    `json:"Address2"`
        city  string    `json:"city"`
        state  string    `json:"state"`
        zipcode  string    `json:"zipcode"`
}

func main() {
    jsonData := `{  "Address1": "777 Brockton Avenue",
  "Address2": "string",
  "city": "Abington",
  "state": "MA",
  "zipcode": "2351"}`
    var person Address
    err := json.Unmarshal([]byte(jsonData), &person)
    if err != nil {
        panic(err)
    }
    xmlData, err := xml.Marshal(person)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(xmlData))
}

The output is as below

<Address><Address1>777 Brockton Avenue</Address1><Address2>string</Address2></Address>

My expected output is

<?xml version="1.0"?>
<AddressValidateRequest USERID="702DIGIT27hfgjkf41">
  <Address>
    <Address1>777 Brockton Avenue</Address1>
    <Address2>string</Address2>
    <City>Abington</City>
    <State>MA</State>
    <Zip5>2351</Zip5>
    <Zip4/>
  </Address>
</AddressValidateRequest>

I am quite new to the language,any guidance is much appreciated


Solution

  • Create another struct as AddressValidateRequest with Name, UserID and Address fields. As this structure is defined based on the output you expected.

    Also first character should be in uppercase letter for the City, State and Zipcode fields. If not they'll not included in the xml output.

    Here is the code

    package main
    
    import (
        "encoding/json"
        "encoding/xml"
        "fmt"
    )
    
    type Address struct {
        Address1 string `json:"Address1"`
        Address2 string `json:"Address2"`
        City     string `json:"city"`
        State    string `json:"state"`
        Zip5     string `json:"zipcode"`
        Zip4     string `json:"Zip4"`
    }
    
    type AddressValidateRequest struct {
        Name string  `xml:"AddressValidateRequest"`
        UserID  string  `xml:"USERID,attr"`
        Address Address `xml:"Address"`
    }
    
    func main() {
        jsonData := `{  
            "Address1": "777 Brockton Avenue",
            "Address2": "string",
            "city": "Abington",
            "state": "MA",
            "zipcode": "2351"
        }`
    
        var person Address
        err := json.Unmarshal([]byte(jsonData), &person)
        if err != nil {
            panic(err)
        }
    
        req := AddressValidateRequest{
            UserID:  "702DIGIT2741",
            Address: person,
        }
    
        xmlData, err := xml.MarshalIndent(req, "", " ")
        if err != nil {
            panic(err)
        }
    
        fmt.Printf("%s%s \n", xml.Header, string(xmlData))
    
    }