json_xml_case.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // json_xml_case.go
  2. package main
  3. import (
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "log"
  8. "strings"
  9. )
  10. type thing struct {
  11. Field1 int
  12. Field2 string
  13. }
  14. func main() {
  15. x := `<x><field1>423</field1><field2>hello from xml</field2></x>`
  16. j := `{"field1": 423, "field2": "hello from json"}`
  17. tx := thing{}
  18. if err := xml.Unmarshal(strings.NewReader(x), &tx); err != nil {
  19. log.Fatalf("Error unmarshaling XML: %v", err)
  20. }
  21. tj := thing{}
  22. if err := json.Unmarshal([]byte(j), &tj); err != nil {
  23. log.Fatalf("Error unmarshaling JSON: %v", err)
  24. }
  25. fmt.Printf("From JSON: %#v\n", tj)
  26. fmt.Printf("From XML: %#v\n", tx)
  27. }
  28. /* Output with
  29. type thing struct {
  30. Field1 int
  31. Field2 string
  32. }:
  33. From XML: main.thing{Field1:0, Field2:""} // All matching is case sensitive!
  34. From JSON: main.thing{Field1:423, Field2:"hello from json"}
  35. Output with
  36. type thing struct {
  37. field1 int
  38. field2 string
  39. }:
  40. 2012/02/22 10:51:11 Error unmarshaling JSON: json: cannot unmarshal object
  41. field1" into unexported field field1 of type main.thing
  42. JSON uses reflection to unmarshal!
  43. */