How do I convert an escaped JSON string within a JSON object?

后端 未结 4 2066
[愿得一人]
[愿得一人] 2020-11-27 08:07

I\'m receiving a JSON object from a public API with a property that, itself, is an escaped JSON string.

{
   \"responses\":[
      {
         \"info\":\"keep         


        
4条回答
  •  臣服心动
    2020-11-27 08:11

    1. you can deserialize it into an intermediary class that has a property: string Body {get; set;}
    2. deserialize the "body" string into it's appropriate type
    3. create a new instance of your a class that represents your destination model.
    4. serialize that model

    Here's a program that does it with the dynamic type and anonymous objects.

    static void Main(string[] args)
    {
        var json = File.ReadAllText("JsonFile1.json");
        dynamic obj = JsonConvert.DeserializeObject(json);
    
        var dest = new
        {
            responses = ((IEnumerable)obj.responses).Select(x => new
            {
                info = x.info,
                body = JsonConvert.DeserializeObject((string)x.body)
            })
        };
    
        var destJson = JsonConvert.SerializeObject(dest);
        File.WriteAllText("JsonFile2.json", destJson);
    }
    

    Alternatively, you can just construct a new version of whatever your destination type is instead of an anonymous type, if you don't feel like reserializing the josn.

提交回复
热议问题