2

I have a question about System.Text.Json.deserialize. I have got the Json value like this

    {
        "id" :"1",
        "ShopName" :"Paint Shop",
        "Books" : [1,2]
    }

It can easy convert to simple object as

    public class bookstore {
        public int id {get;set}
        public string ShopName {get;set}
        public IEnumerable<int> Books {get;set}
    }

But I have a function which convert books array int into list of object like this

    {
        "id" :"1",
        "ShopName" :"Paint Shop",
        "Books" : [
            {
                "bookId":1,
                "bookName":"Peter Pan",
                "location":"A01"
            },
            {
                "bookId":2,
                "bookName":"Cooking Book",
                "location":"A02"
            }
        ]
    }

Right now, I want to modify the value of Books[1].location value, by using jsonnode.parse(string) to convert the object. Can I know how to do it ?

Thank you

2
  • This looks wrong: public IEnumerable<int> Books {get;set} It should be public IEnumerable<Book> Books {get;set} where Book is a class containing book properties. Commented Oct 18, 2022 at 4:58
  • 1
    Once you have that, you can deserialize everything and access the location property of the books. Commented Oct 18, 2022 at 5:00

3 Answers 3

3

Don't know why you want to use the JsonNode.Parse().

If you just want to modify the location's value, maybe you can use the JsonSerializer with BookStore and Book class to help you.
📌 The Book class is a IEnumerable property of BookStore.

an example by .NET6 Console App
📌 BookClass is a 2-level nested class

// See https://aka.ms/new-console-template for more information
using System.Text.Json;

// Initialize json string
string jsonStr = "{\"id\": 1, \"ShopName\" :\"Paint Shop\", \"Books\" : [\r\n            {\r\n                \"bookId\":1,\r\n                \"bookName\":\"Peter Pan\",\r\n                \"location\":\"A01\"\r\n            },\r\n            {\r\n                \"bookId\":2,\r\n                \"bookName\":\"Cooking Book\",\r\n                \"location\":\"A02\"\r\n            }\r\n        ]\r\n    }";

// Deserilize to object
Bookstore bookstore = JsonSerializer.Deserialize<Bookstore>(jsonStr);

// Write the location's value
Console.WriteLine(bookstore.Books.ToArray()[1].location);

// Modified the location's value
bookstore.Books.ToArray()[1].location += "_Modified";

// Write the modified location's value
Console.WriteLine(bookstore.Books.ToArray()[1].location);

// See result output
Console.ReadLine();

public class Bookstore
{
    public int id { get; set; }
    public string ShopName { get; set; }
    public IEnumerable<Book> Books { get; set; }
}

public class Book
{
    public int bookId { get; set; }
    public string bookName { get; set; }
    public string location { get; set; }
}

Result output image enter image description here


If you persist to use JsonNode.Parse(), then need more steps. like this.

// See https://aka.ms/new-console-template for more information
using System.Text.Json;
using System.Text.Json.Nodes;

// Initialize json string
string jsonStr = "{\"id\": 1, \"ShopName\" :\"Paint Shop\", \"Books\" : [\r\n            {\r\n                \"bookId\":1,\r\n                \"bookName\":\"Peter Pan\",\r\n                \"location\":\"A01\"\r\n            },\r\n            {\r\n                \"bookId\":2,\r\n                \"bookName\":\"Cooking Book\",\r\n                \"location\":\"A02\"\r\n            }\r\n        ]\r\n    }";

// Parse to jsonNode
JsonNode jsonNode = JsonNode.Parse(jsonStr);

// Convert to JsonObject
JsonObject jsonObject = jsonNode.AsObject();

// Convert Books to Json Array
JsonArray jsonArray = jsonObject["Books"].AsArray();

// Convert index 1 in array to Json object
JsonObject book1Object = jsonArray[1].AsObject();

// Write the location value 
Console.WriteLine(book1Object["location"]);

// Modify location value 
book1Object["location"] += "_modified";

// Write the modified location value 
Console.WriteLine(book1Object["location"]);

// See output
Console.ReadLine();

public class Bookstore
{
    public int id { get; set; }
    public string ShopName { get; set; }
    public IEnumerable<Book> Books { get; set; }
}

public class Book
{
    public int bookId { get; set; }
    public string bookName { get; set; }
    public string location { get; set; }
}


Other suggestion

Use Newtonsoft.Json is better. Because when convert a json to a C# object, will need to convert many properties with different value type. The Newtonsoft.Json had already handle these situation, at the mean time the System.Text.Json does not.

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

Comments

1

You can use JObject to modify json directly

var jObject = JObject.Parse(json);

jObject["Books"][1]["location"] = "new value";

Result:

enter image description here

Note:

You should add Newtonsoft.Json package.

Comments

0

Since you are using System.Text.Json, you can change value using this code

var jsonParsed=JsonNode.Parse(json);
jsonParsed["Books"][1]["location"]="A03";

after this , if you need you can get an updated json

json = System.Text.Json.JsonSerializer.Serialize(jsonParsed, new JsonSerializerOptions {WriteIndented=true});

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.