登录
首页 >  Golang >  Go问答

如何在 go 中为内部包含对象数组的对象创建结构?

来源:stackoverflow

时间:2024-04-18 17:45:34 324浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何在 go 中为内部包含对象数组的对象创建结构?》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我在前端使用vuejs,在后端使用go语言。我的 data 变量具有以下格式的数据。

var data = {
    software_type: this.$props.selected,
    selected_solutions: this.fromchildchecked,
  };

通过执行 console.log(data)in 前端,我得到以下输出。

在后端,我有这种格式的结构:

type technology struct {
    id                primitive.objectid `json:"_id,omitempty" bson:"_id,omitempty"`
    softwaretype      string             `json:"software_type" bson:"software_type"`
    selectedsolutions struct {
        selectedsolutions []string
    } `json:"selected_solutions" bson:"selected_solutions"`
}

我非常确定我遇到的问题,这可能是由于我发送的数据格式和我制作的结构不同造成的。 我使用 mongodb 作为数据库。 通过提交表单,数据以以下格式进入数据库,这意味着我得到了 selected_solutions 的空对象。

{
"_id":{"$oid":"5f5a1fa8885112e153b5a890"},
"software_type":"cross-channel campain mangment software",
"selected_solutions":{}
}

这是我希望在数据库上使用的格式或类似于下面的格式。

{
    "_id":{"$oid":"5f5a1fa8885112e153b5a890"},
    "software_type":"cross-channel campain mangment software",
    "selected_solutions":{
         adobe campaign: ["business to customer (b2c)", "business to business (b2b)"],
         marin software: ["e-government", "m-commerce"],
     }
}

如何更改结构以使其与我尝试发送的数据兼容?预先感谢您的帮助。

编辑:这就是我提交数据的方式。

postuserdetails() {
      var data = {
        software_type: this.$props.selected,
        selected_solutions: this.fromchildchecked,
      };
      console.log(data);
      const requestoptions = {
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: json.stringify(data),
      };
      fetch("http://localhost:8080/technology", requestoptions)
        .then((response) => {
          response.json().then((data) => {
            if (data.result === "success") {
              //this.response_message = "registration successfull";
              console.log("data posted successfully");
            } else if (data.result === "er") {
              //  this.response_message = "reagestraion failed please try again";
              console.log("failed to post data");
            }
          });
        })
        .catch((error) => {
          console.error("error is", error);
        });
    },
    mounted() {
      this.postuserdetails();
    },

这是后端控制器的函数。

//TechnologyHandler handles checkbox selection for technology section
func TechnologyHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("content-type", "application/json")
    w.Header().Add("Access-Control-Allow-Credentials", "true")
    var technologyChoices model.Technology
    //var selectedSolution model.Selected
    //reads request body and and stores it inside body
    body, _ := ioutil.ReadAll(r.Body)
    //body is a json object, to convert it into go variable json.Unmarshal()is used ,
    //which converts json object to User object of go.
    err := json.Unmarshal(body, &technologyChoices)
    var res model.TechnologyResponseResult

    if err != nil {
        res.Error = err.Error()
        json.NewEncoder(w).Encode(res)
        return
    }

    collection, err := db.TechnologyDBCollection()
    if err != nil {
        res.Error = err.Error()
        json.NewEncoder(w).Encode(res)
        return
    }

    _, err = collection.InsertOne(context.TODO(), technologyChoices)
    if err != nil {
        res.Error = "Error While Creating Technology choices, Try Again"
        res.Result = "er"
        json.NewEncoder(w).Encode(res)
        return
    }

    res.Result = "success"
    json.NewEncoder(w).Encode(res)
    return
}

解决方案


根据您的数据库结构,selected_solutions 是一个包含字符串数组的对象:

type Technology struct {
    ID                primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
    SoftwareType      string             `json:"software_type" bson:"software_type"`
    SelectedSolutions map[string][]string `json:"selected_solutions" bson:"selected_solutions"`
}

今天关于《如何在 go 中为内部包含对象数组的对象创建结构?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>