How to serialize or deserialize a JSON Object to a certain depth in C#?

后端 未结 4 1066
鱼传尺愫
鱼传尺愫 2020-12-05 14:03

I only want the first depth level of an object (I do not want any children). I am willing to use any library available. Most libraries will merely throw an exception when

4条回答
  •  盖世英雄少女心
    2020-12-05 15:01

    You could use reflection to inspect the object and make a copy that changes each property value as needed. Coincidentally I've just made public a new library that makes this kind of thing really easy. You can get it here: https://github.com/jamietre/IQObjectMapper

    Here's an example of the code you would use

    var newInstance = ObjectMapper.Map(obj,(value,del) => {
        return value !=null && value.GetType().IsClass ?
            null :
            value;
        });
    

    The "Map" method iterates through each property of the object, and calls a Func for each (IDelegateInfo having reflection info such as the property name, type, etc.). The function returns the new value for each property. So in this example, I just test the value of each property to see if it's a class, and if so, return null; if not, return the original value.

    Another more expressive way to do it:

    var obj = new MyObject();
    
    // map the object to a new dictionary        
    
    var dict = ObjectMapper.ToDictionary(obj);
    
    // iterate through each item in the dictionary, a key/value pair
    // representing each property 
    
    foreach (KeyValuePair kvp in dict) {
        if (kvp.Value!=null && kvp.Value.GetType().IsClass) {
            dict[kvp.Key]=null;
        }
    }
    
    // map back to an instance
    
    var newObject = ObjectMapper.ToNew(dict);
    

    In either case, the value of newInstance.myChildren (and any other properties that are non-value-typed) will be null. You could easily change the rules for what happens in this mapping.

    Hope this helps. Btw - from your comment it sounds like JSON isn't really your goal but just something you thought would help you achieve it. If you want to end up with json, just serialize the output of this, e.g.

    string json = JavaScriptSerializer.Serialize(newObject);
    

    But I wouldn't involve json if that is was just a means to an end; if you want to stay in CLR objects then no real need to use JSON as an intermediary.

提交回复
热议问题