0

I have a json object which may contain different types for a property. e.g. that status property can have a single string or an object. How can I deserialize this json object using JavaScriptSerializer? (not JsonConverter in json.net )

{"result":
    [
        {"grn":"12345678","status":{"message":"Partnership successfully listed!","partnership_info":null}},
        {"grn":"12345612","status":"Partnership is already listed!"}
    ]
}
Grace
  • 33
  • 1
  • 7
  • You are trying to cross the divide between a loosely-typed language (javascript / node / typescript / other horrible scripting language) and a strongly-typed language (C#). There is no easy way to go about doing this. It would be way easier to change the code that is producing the json so that the json documents it emits follow a consistent format that the serializer can project into a C# class. The issue you are facing is design rather than implementation. – Dave Holden Mar 03 '21 at 01:18
  • Unfortunately the JSON response is from an external API and I don't have access to the source code. – Grace Mar 03 '21 at 01:27
  • Do you have to use [tag:javascriptserializer]? This serializer is very old, is deprecated, and hasn't even been ported to .NET Core / .NET 5. Any possibility to use [tag:json.net] or [tag:system.text.json] instead? – dbc Mar 03 '21 at 05:17
  • `JavaScriptSerializer` is quite inconvenient here because [`JavaScriptConverter`](https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptconverter) only works for JSON **objects** (e.g. `{"message":"...","partnership_info":null}`) and not primitives like `"Partnership is already listed!"`... – dbc Mar 03 '21 at 05:20
  • So you would need to create a converter for the containing object `{"grn"...}` along the lines of [Deserialize a json field with different data types without using Newtonsoft json but with System.Web.Script.Serialization.JavaScriptSerializer](https://stackoverflow.com/q/44434468/3744182). – dbc Mar 03 '21 at 05:21

0 Answers0