簡體   English   中英

如何將 object 中的字符串序列化為有效的 json?

[英]How to serialize string inside object as valid json?

示例:我有 3 節課

    public class A
    {
        public int id;
        public string data;
    }

    public class B
    {
        public int id;
        public List<C> data;
    }

    public class C
    {
        public int test;
    }

用法:

    var a = new A
    {
        id = 21,
        data = "[{\"test\": 123}]"
    };

    var text = JsonSerializer.Serialize(a);

    var c = JsonSerializer.Deserialize<B>(text);

Class A 我用於將數據存儲在 DynamoDb、class B 和 C 作為返回類型;

How to properly map json array inside json to class BI were trying to use default JsonSerializer and NewtonsoftJson, but both of them threw exceptions

應該是這樣的

var c=new C(){ test=..};
var b=new B() { id=.., data= new List<C>{c}};

 var a = new A
    {
        id = b.Id,
        data = JsonSerializer.Serialize(b.data)
    };

或者這個(真的很難理解你想要什么)

var b= new B
{
     it= a.Id,
     data=JsonSerializer.Deserialize<List<C>>(a.data)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM