1

I'm deserializing (or parsing) a json string to a c# object (using Json.NET) and getting a JObject. I want to iterate all the properties with the key "bla", in the same way iterating all xml elements that named "bla" with XElement.Elements("bla").

If it's not possible, I would like to deserialize my json string into a c# object, and work dynamically and recursively on my deserialized json object (my json string can have lists / arrays that can have objects of 2 types. In the end after editing my object (changing values and removing or adding properties) I need to serialize my object back to a json string. Which is the best and easiest way to use json serializing and deserializing?

my Json looks like this:

{"Families":{"Family":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}, {"propA":"dhsj", "propB":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}, {"propA":"dhsj", "propB":"fghfgh"}]}]}

in conclusion, the json value is a json object that it's value is a list/array, the list/array can contain 2 "types" of objects, and one of these types also has a property which it's value is a json object that it's value is a list/array, and it goes like this recursively. sometimes the value of one of the props of the type that doesn't have a property which it's value is a json object that it's value is a list/array, can be a list/array itself, that can contain only 1 type of the two mentioned.

4
  • 2
    What have you tried? Commented Apr 18, 2016 at 17:52
  • Did you look at the methods in JObject? They do exactly that. Commented Apr 18, 2016 at 17:53
  • I didn't find a method of JObject that is similar to iterating XElement.Elements("bla") which gives me every element that is named bla. Commented Apr 18, 2016 at 18:45
  • I tweaked my answer to fit your JSON, iterate recursively to N-levels and add properties dynamically. Commented Apr 18, 2016 at 20:33

3 Answers 3

2

If you don't need a strongly-typed object, you can deserialize to a dictionary:

Dictionary<string, object> myObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

And then just use it as a dictionary:

myObject["Property"] = value;

Or

foreach(var propertyKey in myObject.Keys)
{
  // do something with each property
  Console.WriteLine($"{propertyKey} = {myObject[propertyKey]}");
}

Here's a fiddle

You can serialize it back after you are done

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

2 Comments

A JObject is an dictionary, so you even need to change that part.
@JonathanAllen I didn't know that, but makes sense
0

My json looks more like this:

{"Familys":{"Family":[{"propA":"dhsj", "propB":"dhdisb"}, {"propA":"krbsbs", "propC":"ksndbd", "propD":"odndns", "Families":{"Family":[....]}}]} 

Comments

0

For JSON like this:

var json = @"{
    ""Families"":{
        ""Family"":[
            {
            ""propA"":""Top""
            },
            {
            ""propA"":""Top.Lower"",
            ""Families"":{
                ""Family"":[
                    {
                        ""propB"":""propB value""
                    },
                    {
                        ""propA"":""Top.Lower.EvenLower"",
                        ""Families"":{
                        ""Family"":[
                            {
                                ""propA"":""Top.Lower.EvenLower.EvenLower""
                            }
                        ]
                        }
                    }
                ]
            }
            }
        ]
    }
}";

Do something like this:

//calling code makes use of "dynamic" to make things clean and readable.
dynamic parsedJson = JsonConvert.DeserializeObject(json);
var allPropAValues = GetPropAValues(parsedJson);
//**** NOTE: this has our extra property ****
var jsonWithExtraStuffProperty = JsonConvert.SerializeObject(parsedJson);

//recursive function that reads AND writes properties
public static List<string> GetPropAValues(dynamic obj)
{
    var propAValues = new List<string>();

    //**** NOTE: the use of an added property ****
    obj.ExtraStuff = new Random().Next();

    //if we have a propA value, get it.
    if (obj.propA != null)
        propAValues.Add(obj.propA.Value);

    //iterate through families if there are any. your JSON had Families.Family.
    if (obj.Families != null)
        foreach (dynamic family in obj.Families.Family)
            propAValues.AddRange(GetPropAValues(family));

    return propAValues;
}

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.