Newton.Json convert dynamic variable to JObject RRS feed

  • Question

  • User-148788041 posted


    i tried

    dynamic str = Newtonsoft.Json.JsonConvert.DeserializeObject(file.ReadAllText())
    i want to convert str to JObject
    JObject strObj = JObject.Parse(str);
    Shows error.

    Friday, August 10, 2018 5:38 PM

All replies

  • User753101303 posted


    The error being that it expects a string ?? Seems you want something like such as :

    JObject strObj = JObject.Parse(file.ReadAllText(filePath));

    or you want to have both a JObject and a dynamic object deseriazlized from the same source. If it doesn't help please explain your intent.

    Friday, August 10, 2018 8:11 PM
  • User-148788041 posted
    After deserailzation i need to convert to JObject.
    Saturday, August 11, 2018 1:16 AM
  • User753101303 posted

    I mean a higher level view of your exact goal. For now I would just use :

    const string json=@"{""a"":""Hello"",""b"":12}"; // in your case it is just loaded from a file
    var a = JObject.Parse(json);
    foreach (var p in a.Properties()) Console.WriteLine(p.Value);

    For now you are going through a str dynamic object. It seems you are thinking it is a string but it is not which is why JObject.Parse(str) fails.

    It is actually already a JObject that you could cast or you could use generics but using JObject.Parse seems just more direct.

    Saturday, August 11, 2018 9:29 AM
  • User753101303 posted

    For example note that a, b, c, d can all be used with the Test method and are all giving the same output. d seems the more straightforward if you really need a JObject.

            static void Test(JObject o)
                foreach (var p in o.Properties())
            static void Main(string[] args)
                const string json=@"{""a"":""Hello"",""b"":12}";
                dynamic a = JsonConvert.DeserializeObject(json);
                var b = (JObject)a;
                var c = JsonConvert.DeserializeObject<JObject>(json);
                var d = JObject.Parse(json);

    Saturday, August 11, 2018 9:44 AM