Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to check for NULL or a single object in a list returned by JSON deserialization using Newtonsoft JSON.NET in C#
    primarykey
    data
    text
    <p>I am deserializing a JSON result as follows:</p> <pre><code>responsebody = WebClient.DownloadString(URI); Console.WriteLine(responsebody); if (string.IsNullOrEmpty(responsebody)) { throw new Exception("The request returned empty Position Object."); } if (responsebody.Length &gt; 0) { //dynamic dynObj = JsonConvert.DeserializeObject(responsebody); //if (dynObj.positions == null) //{ // throw new Exception("The request returned empty Position Object."); //} RootPositions PosList = JsonConvert.DeserializeObject&lt;RootPositions&gt;(responsebody); if (PosList.positions.position.Count() &gt; 1) foreach (var p in PosList.positions.position) { Console.WriteLine("Id : {0}", p.id); Console.WriteLine("Symbol : {0}", p.symbol); Console.WriteLine("Quantity : {0}", p.quantity); Console.WriteLine("Average Price : {0}", p.cost_basis); } } return responsebody; </code></pre> <p>The class for the above deserialization is as follows:</p> <pre><code>//******** JSON Object to PositionData Class public class RootPositions { public PositionList positions { get; set; } } public class PositionList { //[JsonConverter(typeof(GenericListCreationJsonConverter&lt;Position&gt;))] public List&lt;Position&gt; position { get; set; } } public class Position { public float cost_basis { get; set; } public int id { get; set; } public decimal quantity { get; set; } public string symbol { get; set; } } </code></pre> <p>My code doesnt work the way I am handling if I get a NULL JSON result as below.</p> <p>JSON returned: <code>"{\"positions\":\"null\"}"</code> or {"positions":"null"}</p> <pre><code>Newtonsoft.Json.JsonSerializationException: {"Error converting value \"null\" to type 'ApiPost.PositionList'. Path 'positions', line 1, position 19."} System.ArgumentException: Could not cast or convert from System.String to ApiAddIn.PositionList. </code></pre> <p>How can I check for NULL and also how can I check if the JSON is giving back a Position List or only 1 position. Greatly appreciate your help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload