简体   繁体   中英

How can i make a flat object by removing keys in C#?

I am really not sure if this could be achievable, How can i remove some nested keys in an Object and make the object very flat. I have a dynamic object as follows,

EventData": { "ChangeSet": { "Change": { "changes": [ ] } } }

and i want to change the above to

EventData": { [] }

is this can be achieved in C#?

Use the NewtonSoft.JSon package.. Following code does the trick. I made it a string array because I do not know what you need but you can change this to your liking.

const string complex = "{\"EventData\": { \"ChangeSet\": { \"Change\": { \"changes\" : [ ]}}}}";

Call to method:

string simple = returnSimpleObject(complex);


        public class SerializeData
        {
             public string[] EventData { get; set; }
        }

        private static string returnSimpleObject(string Json)
        {
            JObject jobject = JObject.Parse(Json);

            JToken tEventData = jobject.SelectToken("EventData");
            SerializeData myEvent = tEventData.ToObject<SerializeData>();

            JToken tchanges = jobject.SelectToken("EventData.ChangeSet.Change.changes");
            myEvent.EventData = tchanges.ToObject<string[]>();


            JsonSerializer serializer = new JsonSerializer();
            StringWriter strWrite = new StringWriter();
            JsonWriter myWriter = new JsonTextWriter(strWrite);
            serializer.Serialize(myWriter, myEvent);
            return strWrite.ToString();

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM