我有一个像这样的对象结构:
public class Proposal {
public List<ProposalLine> Lines { get; set; }
public string Title { get; set; }
}
public class ProposalLine {
public Proposal Proposal { get; set; } // <- Reference to parent object
}
Run Code Online (Sandbox Code Playgroud)
我尝试将Proposal序列化为Json,它告诉我有一个循环引用,这是正确的.
不幸的是,我无法触摸对象,因为它们位于另一个项目的引用DLL中 - 否则我会更改它们.
有没有办法序列化为Json并忽略圆形属性?
考虑这种情况!
成功执行http请求后,如果执行json编码出错怎么办,如何覆盖头代码
func writeResp(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
//Here I set the status to 201 StatusCreated
w.WriteHeader(code)
s := success{Data: data}
//what if there is an error here and want to override the status to 5xx error
//how to handle error here, panic?, http.Error() is not an option because as we already wrote header to 201, it just prints `http: multiple response.WriteHeader calls`
if err := json.NewEncoder(w).Encode(s); err != nil {
w.Header().Set("Content-Type", "application/json")
//it throws http: …Run Code Online (Sandbox Code Playgroud) 我已经读过这个问题,询问json.Marshal是否可以在任何输入上失败,并根据我的情况看起来的答案,它不会失败.我的情况如下:
我有一个特定的结构(没有嵌套,没有数组,只是字符串,各种类型的整数,bools).我需要把它整理成一个json.它会失败吗?
在更具体的例子中:
type some struct {
F1 string `json:"f1"`
F2 uint32 `json:"f2"`
F3 int64 `json:"f3"`
F4 bool `json:"f4"`
}
func doSomething(s some) (string, error) {
data, err := json.Marshal(s)
if err != nil {
return "", err
}
return string(data), nil
}
Run Code Online (Sandbox Code Playgroud)
可能doSomething会失败吗?如果是,请提供意见,否则解释原因.根据我目前的知识,它不能.