登录
首页 >  Golang >  Go问答

使用 System.Text.Json 在代码中嵌入 JSON 数据

来源:stackoverflow

时间:2024-03-26 10:51:32 346浏览 收藏

在 C# 中使用 System.Text.Json 嵌入 JSON 数据时,可以通过字典实现。将键值对添加到字典中,然后使用 `JsonSerializer.Serialize` 方法将字典序列化为 JSON 文本。

问题内容

我正在寻找 golang 的 json 的等效项:带有 c# 的 system.text.json 的“内联” 标记。

例如,我在 c# 中有以下类结构:

class outer{
    public string hello;
    public inner theinner;
}

class inner{
    public string earth;
    public string moon;
}

我希望序列化和反序列化的 json 文本为

{
   "hello" : "example_value_01",
   "earth" : "example_value_02",
   "moon" : "example_value_03"
}

在 golang 中,我可以通过以下结构定义来实现这一点

type Outer struct{
    Hello string
    TheInner Inner `json: "inline"`
}

type Inner struct{
   Earth string
   Moon string
}

但是,我无法在 c# 的 system.text.json 中找到合适的方法来执行此操作。


正确答案


要在 c# 中实现它,您根本不需要任何自定义类,您可以使用字典

var dict = new dictionary {
                           {"hello","example1"},
                           {"world","example2"}
                           };
                           
var json= system.text.json.jsonserializer.serialize(dict,new jsonserializeroptions { writeindented = true});

结果

{
  "hello": "example1",
  "world": "example2"
}

但是如果您想要一种困难的方式,那么使用 newtonsoft.json 会更容易,因为 text.json 几乎所有内容都需要一个自定义序列化器

using Newtonsoft.Json;

    var json = SerializeOuterObj(obj, "TheInner");
    obj = DeserializeOuterObj(json);

public string SerializeOuterObj(object outerObj, string innerObjectPropertyName)
{
    var jsonParsed = JObject.FromObject(outerObj);
    var prop = jsonParsed.Properties().Where(i => i.Name == innerObjectPropertyName).First();
    prop.Remove();
    foreach (var p in ((JObject)prop.Value).Properties())
        jsonParsed.Add(p.Name, p.Value);
    return jsonParsed.ToString();
}
public Outer DeserializeOuterObj(string json)
{
    var jsonParsed = JObject.Parse(json);
    var outer = jsonParsed.ToObject();
    outer.TheInner = jsonParsed.ToObject();
    return outer;
}

到这里,我们也就讲完了《使用 System.Text.Json 在代码中嵌入 JSON 数据》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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