Convert JSON String to JSON Object c#

I have this String stored in my database:

str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }"

This string is already in the JSON format but I want to convert it into a JObject or JSON Object.
JObject json = new JObject();

I tried the json = (JObject)str; cast but it didn’t work so how can I do it?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation.

Method 2

if you don’t want or need a typed object try:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)

Method 3

This works

    string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
    JavaScriptSerializer j = new JavaScriptSerializer();
    object a = j.Deserialize(str, typeof(object));

Method 4

You can try like following:

string output = JsonConvert.SerializeObject(jsonStr);

Method 5

there’s an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes

Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented .
In this manner you will use these classes which is more powerful and simply to use.

Method 6

This works for me using JsonConvert

var result = JsonConvert.DeserializeObject<Class>(responseString);

Method 7

If your JSon string has “” double quote instead of a single quote ‘ and has n as a indicator of a next line then you need to remove it because that’s not a proper JSon string, example as shown below:

            SomeClass dna = new SomeClass ();
            string response = wc.DownloadString(url);
            string strRemSlash = response.Replace(""", "'");
            string strRemNline = strRemSlash.Replace("n", " ");
            // Time to desrialize it to convert it into an object class.
            dna = JsonConvert.DeserializeObject<SomeClass>(@strRemNline);

Method 8

This does’t work in case of the JObject this works for the simple json format data. I have tried my data of the below json format data to deserialize in the type but didn’t get the response.

For this Json

  "Customer": {
    "id": "Shell",
    "Installations": [
        "id": "Shell.Bangalore",
        "Stations": [
            "id": "Shell.Bangalore.BTM",
            "Pumps": [
                "id": "Shell.Bangalore.BTM.pump1"
                "id": "Shell.Bangalore.BTM.pump2"
                "id": "Shell.Bangalore.BTM.pump3"
            "id": "Shell.Bangalore.Madiwala",
            "Pumps": [
                "id": "Shell.Bangalore.Madiwala.pump4"
                "id": "Shell.Bangalore.Madiwala.pump5"

Method 9

In a situation where you are retrieving a list of objects of a certain entity from your api, your response string may look like this:


In this situation you may want an array of Jason objects and cycle through them to populate your c# variable. I’ve done like so:
var httpResponse = await Http.GetAsync($"api/{entidadeSelecionada}");
    List<List<string[]>> Valores = new();
    if (httpResponse.IsSuccessStatusCode)
        //totalPagesQuantity = int.Parse(httpResponse.Headers.GetValues("pagesQuantity").FirstOrDefault());
        //Aqui tenho que colocar um try para o caso de ser retornado um objecto vazio
        var responseString = await httpResponse.Content.ReadAsStringAsync();

        JArray array = JArray.Parse(responseString);

        foreach (JObject objx in array.Children<JObject>())
            List<string[]> ls = new();
            foreach (JProperty singleProp in objx.Properties())
                if (!singleProp.Name.Contains("_xyz"))
                    string[] val = new string[2];
                    val[0] = singleProp.Name;
                    val[1] = singleProp.Value.ToString();
    return Valores;

I achieved this solution by the @Andrei answer.

Method 10

string result = await resp.Content.ReadAsStringAsync();
            List<ListView11> _Resp = JsonConvert.DeserializeObject<List<ListView11>>(result);
            //List<ListView11> _objList = new List<ListView11>((IEnumerable<ListView11>)_Resp);

            IList usll = _Resp.Select(a => a.lttsdata).ToList();
            // List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
            //IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
            Lv.ItemsSource = usll;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x