Splendid
Splendid

Reputation: 1357

Unmarshal _id to id wont work

So my structure looks like this:

type Article struct {
    ID bson.ObjectId `json:"id" bson:"_id,omitempty"`
    LangCode string `json:"langCode" bson:"langCode"`
    AuthorId string `json:"authorId" bson:"authorId"`
    AuthorName string `json:"authorName" bson:"authorName"`
    ArticleType int64 `json:"type" bson:"type"`
    Title string `json:"title" bson:"title"`
    Intro string `json:"intro" bson:"intro"`
    Body string `json:"body" bson:"body"`
    MainPic string `json:"mainPic" bson:"mainPic"`
    Tags string `json:"tags" bson:"tags"`
    Slug string `json:"slug" bson:"slug"`
    DateAdded time.Time `json:"dateAdded" bson:"dateAdded"`
    Status int64 `json:"status" bson:"status"`
}

And following snippet:

pageReturn.Pagination = resultsList.Pagination
err = json.Unmarshal(resultsList.Results, &pageReturn.Articles)

Will return data without value _id from database (I mean in json string id will be equal to "")

If I change ID bson.ObjectId json:"id" bson:"_id,omitempty" to ID bson.ObjectId json:"_id" bson:"_id,omitempty"

value will be returned normally (actual _id value from db will be returned)

I'm wondering how can I avoid this (but I still need to use json.Unmarshal)

Upvotes: 0

Views: 915

Answers (1)

Stephane Martin
Stephane Martin

Reputation: 1642

  • Unmarshal into your Article struct, but with tag json:"_id"
  • two struct types that only differ by tags can be converted to each other. So one solution is to create another ArticleBis type, with tag json:"id" instead. Then you convert your article to an ArticleBis instance, which you Marshal.

Another simple example:

package main

import "fmt"
import "encoding/json"

type Base struct {
    Firstname string `json:"first"`
}

type A struct {
    Base
    Lastname string `json:"last"`
}

type B struct {
    Base
    Lastname string `json:"lastname"`
}

func main() {
    john := A{Base: Base{Firstname: "John"}, Lastname:"Doe"}
    john1 := B(john)
    john_json, _ := json.Marshal(john)
    john1_json, _ := json.Marshal(john1)
    fmt.Println(string(john_json))
    fmt.Println(string(john1_json))
}

Upvotes: 1

Related Questions