相关疑难解决方法(0)

如何将带有循环引用的对象结构序列化为Json?

我有一个像这样的对象结构:

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并忽略圆形属性?

c# wcf serialization json

5
推荐指数
1
解决办法
1万
查看次数

http在golang中覆盖http标头代码,而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)

error-handling http go net-http

3
推荐指数
1
解决办法
3582
查看次数

假设特定结构上的json.Marshall不可能失败是否安全?

我已经读过这个问题,询问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会失败吗?如果是,请提供意见,否则解释原因.根据我目前的知识,它不能.

go

0
推荐指数
1
解决办法
119
查看次数

标签 统计

go ×2

c# ×1

error-handling ×1

http ×1

json ×1

net-http ×1

serialization ×1

wcf ×1