3

I have a JSON file I'm reading from text and parsing it into JObject using Newtonsoft.Json.Linq. The JSON file looks like this:

{  
   "EntityTypeDto":[  
      {  
         "EntityType":"Grade",
         "Language":"ES"
      },
      {  
         "EntityType":"ApplicationType",
         "Language":"ES"
      },
      {  
         "EntityType":"Borough",
         "Language":"ES"
      }

   ]
}

Using the Newtonsoft library, are there any methods I can leverage on JObject to replace the Language property of all the objects to another value? If not what would be another way to do this? This project is a console application in C#, VS 2012, thanks.

2 Answers 2

4

You don't need Linq here to achieve what you need , Linq is for consult data, not for modify it. So you can just, eg, a foreach to iterate and modify the elements of the array:

JObject json= JObject.Parse(jsonString);
JArray entityTypeDtos= (JArray)json["EntityTypeDto"];
foreach(var e in entityTypeDtos)
{
  if(e["Language"] != null)
     e["Language"]="EN";
}
Sign up to request clarification or add additional context in comments.

7 Comments

After I make those changes, how do I return it back to the JObject (for which you named "json") with the new values?
Debug and check json variable after execute the foreach, you will see the elements will be changed to EN
Json is hierarchical and strcutured like Xml, just much less verbose, that's why it is possible to enumerate and replace, since it suppose to be well formed
@octavioccl, you may need to check e["Language"] != null, to be sure before making a change. Since even W/o Language element in few elements it will be perfect Json
Well, that is true, but I always I left to the OP that kind of validations to focus only in the main problem, anyway thanks for the suggestion ;)
|
2

I'm guessing by the Linq tag you would like a Linq approach try this

string json = @"{  
   'EntityTypeDto':[  
      {  
         'EntityType':'Grade',
         'Language':'ES'
      },
      {  
         'EntityType':'ApplicationType',
         'Language':'ES'
      },
      {  
         'EntityType':'Borough',
         'Language':'ES'
      }
   ]
}";


JObject myjobj = JObject.Parse(json);

JArray EntityType = (JArray)myjobj["EntityTypeDto"];

(from eobj in EntityType 
where eobj["Language"]="ES"
select eobj).ForEach(x => x["Language"]="New Value");

2 Comments

Thanks for this, how would I convert back into the JObject after the Language value is updated?
@user3299379 Foreach is a method of List<T>, also you need to cast:(string)eobj["Language"]="ES"

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.