1

For example, I write code like this

        bool hasCustomer = true;

        JObject j = JObject.FromObject(new
        {
            customer = hasCustomer? new
            {
                name = "mike",
                age = 48
            }:null
        });


        JObject c = (JObject)j["customer"];
        if (c != null)
            string name = (string) c["name"];

This works fine.

But if I set hasCustomer = false;

       JObject c = (JObject)j["customer"];

will throw an System.InValidCastException:

       Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'.

I was expecting should just assign null to JObject c since JObject is nullable.

So, what's the best way to handle something like this?

2 Answers 2

4

Ignoring null, seems to be producing the correct behavior.

    bool hasCustomer = false ;

    JsonSerializer s = new JsonSerializer() {
        NullValueHandling = NullValueHandling.Ignore
    };
    JObject j = JObject.FromObject( new {
        customer = hasCustomer ? new {
            name = "mike" ,
            age = 48
        } : null
    }, s );


    JObject c = (JObject)j[ "customer" ];
Sign up to request clarification or add additional context in comments.

Comments

-1

JObject can be nullable but this does not mean that JObject can cast null. You can try this :

JObject j = JObject.FromObject(new
        {
            customer = hasCustomer? new
            {
                name = "mike",
                age = 48
            }:new Object()
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.