Here's struct of unmarshal target:
type ParsedObjectType struct{
Value struct{
E []struct {
B bool
C float32 `json:"coefficient"`
CE float32
G int `json:"group"`
P float32 `json:"period"`
T int `json:"type"`
}
}
}
And soucre string looks like this:
{"B":false,"C":2.123,"CE":0,"G":1,"P":1000,"T":0}
After json.Unmarshal([]byte(string), ParsedObjectType)
i receive
{
"B": false,
"coefficient": 0,
"CE": 0,
"group": 0,
"period": 0,
"type": 0
}
with zeros instead of source data in properties
As I understand in json
you have compact names, but it should not force you to create cryptic names in structures.
In the code, you should use meaningful names, but in a serialized format you can use synonyms.
Adapted from your example: playground: https://play.golang.org/p/gbWhV3FfHMr
package main
import (
"encoding/json"
"log"
)
type ParsedObjectType struct {
Value struct {
Items []struct {
Coefficient float32 `json:"C"`
Group int `json:"G"`
Period float32 `json:"P"`
TypeValue int `json:"T"`
} `json:"E"`
}
}
func main() {
str := `{"Value": {
"E": [
{
"B": false,
"C": 2.123,
"CE": 0,
"G": 1,
"P": 1000,
"T": 0
}
]
}
}`
out := &ParsedObjectType{}
if err := json.Unmarshal([]byte(str), out); err != nil {
log.Printf("failed unmarshal %s", err)
}
log.Printf("Constructed: %#v", out)
}
If you want to parse {"B":false,"C":2.123,"CE":0,"G":1,"P":1000,"T":0}
to
{
"B": false,
"coefficient": 0,
"CE": 0,
"group": 0,
"period": 0,
"type": 0
}
I think your struct should be declared as
struct {
B bool
coefficient float32 `json:"C"`
CE float32
group int `json:"G"`
period float32 `json:"P"`
type int `json:"T"`
}
You have two big problems:
Your tags are completely wrong. Your input contains, for example "C":2.123
, but your struct tags mean the Unmarshaler is looking for "coefficient":2.123
, which it will never find. To correct this, set the tags to match your input:
type ParsedObjectType struct{
Value struct{
E []struct {
B bool
C float32 `json:"C"`
CE float32
G int `json:"G"`
P float32 `json:"P"`
T int `json:"T"`
}
}
}
Note that now your struct fields match your JSON keys exactly, so you could simply eliminate your JSON tags entirely for simplicity, if you wish:
type ParsedObjectType struct{
Value struct{
E []struct {
B bool
C float32
CE float32
G int
P float32
T int
}
}
}
Your data structure doesn't appear to match your input. Your input appears to be a single object, but your input expects an object within an object. To correct this, (assuming the input you provided in your question is complete), get rid of the extra layer in your data structure:
type ParsedObjectType struct{
B bool
C float32
CE float32
G int
P float32
T int
}