Asked  7 Months ago    Answers:  5   Viewed   37 times
type TestObject struct {
    kind string `json:"kind"`
    id   string `json:"id, omitempty"`
    name  string `json:"name"`
    email string `json:"email"`
}

func TestCreateSingleItemResponse(t *testing.T) {
    testObject := new(TestObject)
    testObject.kind = "TestObject"
    testObject.id = "f73h5jf8"
    testObject.name = "Yuri Gagarin"
    testObject.email = "Yuri.Gagarin@Vostok.com"

    fmt.Println(testObject)

    b, err := json.Marshal(testObject)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(b[:]))
}

Here is the output:

[ `go test -test.run="^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
    {TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
    {}
    PASS

Why is the JSON essentially empty?

 Answers

96

You need to export the fields in TestObject by capitalizing the first letter in the field name. Change kind to Kind and so on.

type TestObject struct {
 Kind string `json:"kind"`
 Id   string `json:"id,omitempty"`
 Name  string `json:"name"`
 Email string `json:"email"`
}

The encoding/json package and similar packages ignore unexported fields.

The `json:"..."` strings that follow the field declarations are struct tags. The tags in this struct set the names of the struct's fields when marshaling to and from JSON.

Ru it on the playground.

Tuesday, June 1, 2021
 
Kemrop
answered 7 Months ago
85

In Yii2 you don't use model() method. Because, Yii2 and Yii1 is different(see more https://github.com/yiisoft/yii2/blob/master/docs/guide/intro-upgrade-from-v1.md). In Yii1 to provide data like that:

Post::model()->find($condition,$params);

In Yii2 to provide data like that:

Post::find()->where(['type' => $id])->all(); 

See more https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md

Delete model in your model:

public static function model($className=__CLASS__)
{
    return parent::model($className);
}

And change loadItems method to:

private static function loadItems($type)
{
    self::$_items[$type]=[];
    $models=self::findAll([
        'condition'=>'type=:$type',
        'params'=>[':type'=>$type],
        'order'=>'position',
    ]);

    foreach ($models as $model)
        self::$_items[$type][$model->code]=$model->name;
}
Saturday, May 29, 2021
 
codingb
answered 7 Months ago
65

Looks like you are attempting to run multiple statements, possibly through a mysql_query() or mysqli->query() which only support single statements. Instead you need to execute this with mysqli->multi_query() or mysql_multi_query().

Saturday, May 29, 2021
 
gMale
answered 7 Months ago
86

Working playground link: http://play.golang.org/p/_r-bQIw347

The gist of it is this; by using the reflect package we loop over the fields of the struct we wish to serialize and map them to a map[string]interface{} we can now retain the flat structure of the original struct without introducing new fields.

Caveat emptor, there should probably be several checks against some of the assumptions made in this code. For instance it assumes that MarshalHateoas always receives pointers to values.

package main

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

type User struct {
    Id   int    `json:"id"`
    Name string `json:"name"`
}

type Session struct {
    Id     int `json:"id"`
    UserId int `json:"userId"`
}

func MarshalHateoas(subject interface{}) ([]byte, error) {
    links := make(map[string]string)
    out := make(map[string]interface{})
    subjectValue := reflect.Indirect(reflect.ValueOf(subject))
    subjectType := subjectValue.Type()
    for i := 0; i < subjectType.NumField(); i++ {
        field := subjectType.Field(i)
        name := subjectType.Field(i).Name
        out[field.Tag.Get("json")] = subjectValue.FieldByName(name).Interface()
    }
    switch s := subject.(type) {
    case *User:
        links["self"] = fmt.Sprintf("http://user/%d", s.Id)
    case *Session:
        links["self"] = fmt.Sprintf("http://session/%d", s.Id)
    }
    out["_links"] = links
    return json.MarshalIndent(out, "", "    ")
}
func main() {
    u := &User{123, "James Dean"}
    s := &Session{456, 123}
    json, err := MarshalHateoas(u)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("User JSON:")
        fmt.Println(string(json))
    }
    json, err = MarshalHateoas(s)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("Session JSON:")
        fmt.Println(string(json))
    }
}
Thursday, August 12, 2021
 
nighter
answered 4 Months ago
12

You can implement a Marshaler like this http://play.golang.org/p/ySUFcUOHCZ (or this http://play.golang.org/p/ndwKu-7Y5m )

package main

import "fmt"
import "encoding/json"

type Deck struct {
    Cards []int
}

func (d Deck) Value() int {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    }
    return value
}
func (d Deck) Size() int {
    return len(d.Cards)
}

func (d Deck) MarshalJSON() ([]byte, error) {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    }

    return json.Marshal(struct {
        Cards []int `json:"cards"`
        Value int   `json:"value"`
        Size  int   `json:"size"`
    }{
        Cards: d.Cards,
        Value: d.Value(),
        Size:  d.Size(),
    })
}

func main() {
    deck := Deck{
        Cards: []int{1, 2, 3},
    }

    b, r := json.Marshal(deck)
    fmt.Println(string(b))
    fmt.Println(r)
}
Monday, November 1, 2021
 
Xel
answered 1 Month ago
Xel
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share