0

I am trying to edit an existing Json File that contains an object called "forge" ("forge" itself is contained within an object called "profiles"), and within that object, I am trying to add another object called resolution that contains height and width. The native application it belongs to can modify and add this element, but I can only seem to be able to read, and write/create all other objects within the forge object except the resolution object and its children.

What it should look like, (circled x indicates what I cannot get render)

But no matter how much I read in newtonsoft documentation, nothing appears to be working. This is what I have written so far. Note that this method is just for overwriting all the contents in the "forge" object, and I tired to add the resolution object, but it fails. Anyone know how to do this? (Connection path is the json file)

My Method

5
  • I should mention, that if that JArray stuff was not there, then it runs fine and overwrites the forge object correctly. Commented Apr 20, 2020 at 22:53
  • @MickyD Would that be more useful? Many tutorials I've seen and read suggest doing it in this fashion, I'm not in love with this so I could create a class to do it, So you are saying the following: Create an object (class) with everything in it, and then instead jsonObj["profiles"]["forge"] = mycreatedclass; then serialize it? Commented Apr 20, 2020 at 23:05
  • 3
    Might you please edit your question to include your code and JSON as text rather than as a screenshot? It's required here not to to use images for textual content, see Discourage screenshots of code and/or errors and Why not upload images of code on SO when asking a question for why. Commented Apr 20, 2020 at 23:37
  • To add an arbitrary POCO to a JObject or JArray you need to serialize it with some overload of JToken.FromObject. See Could not determine JSON object type for type “Class” for example. But I agree that using JObject here seems like an antipattern, which not just serialize an anonymous object? Commented Apr 20, 2020 at 23:39
  • Oh you're reading from some serive, nevermind Commented Apr 21, 2020 at 0:03

1 Answer 1

1

I think the "resolution" is not array, but an object.

Try this

    dynamic forge = new JObject();
    forge.Name = "forge";
    forge.Type = "Brasil";

    dynamic resolutionObj = new JObject();

    resolutionObj.Width = "10";
    resolutionObj.Height = "100"; 

    forge.resolution = resolutionObj;

You will see anything like this:

{
  "Name": "forge",
  "Type": "Brasil",
  "resolution": {
    "Width": "10",
    "Height": "100"
  }
}
Sign up to request clarification or add additional context in comments.

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.