-1

I have a nested class with static properties like this:

public class A {
    public class B {
        public static string BString = null;
    }
}

Here is the JSON:

{
    B {
        "BString" : "Hello"
    }
}

I want to deserialize this JSON so that it sets the nested static value (A.B.BString should contain the string Hello). I don't know a lot about newtonsoft but is there a way to get it to do this without me having to instantiate the B class. I don't want to have to change the class at all to get this to work. I know you can add the [JsonProperty] to static properties to get it to deserialize properly but this does not work with nested classes.

4
  • 3
    Deserialization is about instances. so you might be heading down the wrong track here. (And that data snippet isn't valid JSON.) Commented Jan 27, 2016 at 5:38
  • JsonConvert.DeserializeObject<Class Name>(JsonParams); Commented Jan 27, 2016 at 5:39
  • This is not really possible unless you actively fight the serialization library. As @Wormbo mentioned, JSON represents objects, not namespaces, and typically not static variables. It absolutely is possible to read your custom logic when reading from Newtonsoft, but there's almost definitely a better way to do what you need. Commented Jan 27, 2016 at 5:44
  • 4
    Duplicate of Why can't JSON .Net serialize static or const member variables? or deserializing Static properties using json.net?. Commented Jan 27, 2016 at 5:54

1 Answer 1

1

In general you can't use serialization on static classes. In the case of having a list of two different A-classes, which class would win the race and set the static B-value?

Question: Is it really necessary for you to use a nested (static) class? Whats the reason behind it? Why don't you use a non-nested class?

If you really want to achieve it, there might be a Workaround: Make a new property, in which the static value is set and retrieved. Hopefully this new property will be (de)serialized.

See this dirty example:

public class A
{
    public B SetBProperty 
    { 
        get { return B.BString; } 
        set { B.BString = value; } 
    }

    public class B {
        public static string BString = null;
    }
}

Keep in mind, that in case of the List<A> (de)serialization the last (de)serialized item would win and set the value.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.