Home > Software design >  Parsing json. Field could be plain text and object
Parsing json. Field could be plain text and object

Time:12-23

Shortly, I'm trying to create some web-API-application and I'm parsing telegram data and I am faced up with a problem.

When I get all the JSON, I see that the program can't parse it because some field(text) couldn't resolve the object(code snip below). I'm thinking about creating a custom JSON converter(that's annoying, so that's the reason why I'm here), but maybe I just don't know how to do it correctly.

Here are examples:

{
   "text": "SOME VERY VERY VERY PRIVATE INFORMATION",
},

AND

{
 "text": [
    {
     "type": "link",
     "text": "SOME VERY VERY VERY PRIVATE LINK :D(probably, onlyfans)"
    }
   ],
}

CodePudding user response:

I usually use a JsonConstructor in this case. You don't need to pass all properties into the constructor, you can pass only the properties that cause a problem.

    using Newtonsoft.Json;

    Data data = JsonConvert.DeserializeObject<Data>(json);

public class Data
{
    public List<Text> text { get; set; }

    [JsonConstructor]
    public Data(JToken text)
    {
        if (text.Type == JTokenType.String)
            this.text = new List<Text> { new Text { text = (string)text } };
        else this.text = text.ToObject<List<Text>>();
    }
}

public class Text
{
    public string type { get; set; }
    public string text { get; set; }
}

CodePudding user response:

I would use system.text.json More info here and here

public class Data
{
    [JsonPropertyName("text")]
    public IEnumerable<TextInformation> TextInformations{ get; set; }
}

public class TextInformation
{
    [JsonPropertyName("type")]
    public string Type { get; set; }
    [JsonPropertyName("text")]
    public string Text { get; set; }
}

and use it like this

var text = JsonSerializer.Deserialize<Data>(jsonString)
  • Related