I have a json like below
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1"
}
}
Please suggest how to add
"Address": {
"No": "123",
"Street": "abc"
}
into ContactDetails
This should work (using Newtonsoft.Json)
var json =
#"{
""name"": ""Ram"",
""Age"": ""25"",
""ContactDetails"": {
""MobNo"": ""1""
}
}";
var jObject = JObject.Parse(json);
jObject["ContactDetails"]["Address"] = JObject.Parse(#"{""No"":""123"",""Street"":""abc""}");
var resultAsJsonString = jObject.ToString();
The result is:
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1",
"Address": {
"No": "123",
"Street": "abc"
}
}
}
One of the options would be use Newtonsoft's Json.NET to parse json into JObject, find needed token, and add property to it:
var jObj = JObject.Parse(jsonString);
var jObjToExtend = (JObject)jObj.SelectToken("$.ContactDetails");
jObjToExtend.Add("Address", JObject.FromObject(new { No = "123", Street = "abc" }));
Just Deserialize the JSON into object, then insert the value that you need to insert to it.
Then, Serialize the object into JSON.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
Related
Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.
I have got a following json. I want to merge all nested json objects into one.
[
{
"2": "a",
"3": "a"
},
{
"2": "f",
"3": "a",
"4": "p"
},
{
"2": "n",
"3": "o",
"4": "t"
}
]
so, the output of the above json would be
[
{
"0":"a",
"1":"a",
"2":"f",
"3":"a",
"4":"p",
"5":"n",
"6":"o",
"7":"t"
}
]
I tried to parse the json array and then add all values and append it to another array. However, is there any other elegant solution to merge all nested json objects to one?
Given that you need to change indices, manual merging is unavoidable.
E.g. SelectMany from Linq could be used for merging as:
var input = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(#"
[
{
""2"": ""a"",
""3"": ""a""
},
{
""2"": ""f"",
""3"": ""a"",
""4"": ""p""
},
{
""2"": ""n"",
""3"": ""o"",
""4"": ""t""
}
]");
var result = input
.SelectMany(d => d.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
.Select((value, index) => new {index, value})
.ToDictionary(iv => iv.index, iv => iv.value);
var jsonResult = JsonConvert.SerializeObject(result);
You can use the tool called json .net
Check the following code :
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(sw, model);
JObject o1 = JObject.Parse(#"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(#"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");
o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});
string json = o1.ToString();
// {
// "FirstName": "John",
// "LastName": "Smith",
// "Enabled": true,
// "Roles": [
// "User",
// "Admin"
// ]
// }
Please Check Link :
https://www.newtonsoft.com/json/help/html/MergeJson.htm
i am inserting json format but need to know how i can insert in this format as mention below
{
"products": [
{
"product_id": "55",
"name": "testing data",
"price": "77",
"total": "77",
"quantity": "1",
"type": "kg"
}],
],
"totals": [
{
"code": "sub_total",
"title": "Sub-Total",
"text": "Rs277.00",
"value": "277.0000",
"sort_order": "1"
}]
}
here is my code which i am trying
items local = new items();
foreach (var item in _LocalItem){
local = new items
{
name = item.name
};
}
var json = JsonConvert.SerializeObject(local);
var request = new HttpRequestMessage(HttpMethod.Post, "http://orangepotato.rjcpacking.com/index.php?route=api/login/addcustomerOrder");
request.Content = new StringContent(json);
i dont understand where i can add "products" array in json format
Simply: don't serialize an array - serialize something that has an array in a member called products:
var json = JsonConvert.SerializeObject(new { products = local });
i am trying to get a value from a json file using c#. the json file looks more like the below string.
{
"results": [
{
"address_components": [
{
"long_name": "3",
"short_name": "3",
"types": [
"street_number"
]
}
],
"formatted_address": "3, Puppalaguda - Manikonda Main Rd, Sri Laxmi Nagar Colony, Manikonda, Hyderabad, Telangana 500089, India",
"geometry": {
"bounds": {
"northeast": {
"lat": 17.4025788,
"lng": 78.3748307
},
"southwest": {
"lat": 17.4019665,
"lng": 78.3733937
}
},
"location": {
"lat": 17.4023166,
"lng": 78.37417409999999
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 17.4036216302915,
"lng": 78.37546118029151
},
"southwest": {
"lat": 17.4009236697085,
"lng": 78.3727632197085
}
}
},
"place_id": "EmkzLCBQdXBwYWxhZ3VkYSAtIE1hbmlrb25kYSBNYWluIFJkLCBTcmkgTGF4bWkgTmFnYXIgQ29sb255LCBNYW5pa29uZGEsIEh5ZGVyYWJhZCwgVGVsYW5nYW5hIDUwMDA4OSwgSW5kaWE",
"types": [
"street_address"
]
}
]
}
I am looking for the formatted_address element from the json from C#. I am getting lost in JObject, JArray, JToken. I am trying to use NewtonSoft JSON. Thank you.
Using the LINQ-to-JSON API (JObjects) you can get the formatted address easily using the SelectToken method:
JObject obj = JObject.Parse(json);
string address = (string)obj.SelectToken("results[0].formatted_address");
Console.WriteLine(address);
Fiddle: https://dotnetfiddle.net/Fdvqkl
The easiest way would be to have model objects and then call
var rootObject = JsonConvert.DeserializeObject(jsonString);
With jsonString being your input. Then you can retrieve the formatted_address from the first array element like this like this:
var formattedAddress = rootObject.results[0].formatted_address;
Hope it helps.
using Newtonsoft.Json nuget . and do something like that
static void Main(string[] args)
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
change JTokenType.Array to whatever the type u wish , also change the "results" to the property name you wish to extract
I am trying to create JSON array using Newtonsoft JSON API but its giving me error. I want to achieve structure like
[
{
"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54",
"questions":[
{
"feedback":"6",
"questionid":"1"
},
{
"feedback":"8",
"questionid":"2"
},
{
"feedback":"1",
"questionid":"3"
}
],
"fk_clientid":"24",
"learnerid":"260"
}
]
I want ot add questions array for multiple time but it is giving me error
Can not add property questions to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.
Here is my code:
JArray surveytrackingA = new JArray();
/*code to add
[
{"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54"}]
*/
for (int i = 0; i < surveytrackingA.Count; i++)
{
JObject surveytrackD = (JObject)surveytrackingA[i];
string queryOne = "select * from table101 where fk_curriculumid='"
+ surveytrackD["fk_curriculumid"].ToString()
+ "' and fk_surveyid='"
+ surveytrackD["appsurvey"].ToString() + "'";
JArray questionsA = new JArray();
using (var stmt = await App.localDB.PrepareStatementAsync(queryOne))
{
while (await stmt.StepAsync())
{
JObject questionD = new JObject();
questionD.Add("questionid", stmt.GetTextAt(5));
questionD.Add("feedback", stmt.GetTextAt(6));
questionsA.Add(questionD);
}
}
surveytrackD.Add("questions", questionsA); /*error occurred here when second question array is getting inserted in surveyTrackD*/
surveytrackingA.Add(surveytrackD);
}
Can anyone please correct me. Thanks in advance.
Update:
surveytrackD have the json data,
{
"fk_clientid": "24",
"learnerid": "260",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "completed",
"lastaccessedon": "2014-06-20 09:18:54"
}
You can achieve the same result (JArray in JArray) using regular C# classes and at the end serialize to JSon.
I posted a sample in Github; here a fragment of the code that produces your expected output:
var Surveys = new List<SurveytrackD>();
Surveys.Add( new SurveytrackD { id = "26", appsurvey = "1", fk_curriculumid = "70", status = "Completed", learnerid = "240" } );
Surveys.Add( new SurveytrackD { id = "27", appsurvey = "1", fk_curriculumid = "71", status = "Completed", learnerid = "241" });
foreach (var survey in Surveys)
{
survey.questions = new List<Question>();
survey.questions.Add(new Question { questionid = "1", feedback = "0" });
survey.questions.Add(new Question { questionid = "2", feedback = "1" });
}
var json = JsonConvert.SerializeObject(Surveys, Formatting.Indented);
Console.WriteLine(json);
The output is:
[
{
"fk_clientid": null,
"learnerid": "240",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
},
{
"fk_clientid": null,
"learnerid": "241",
"appsurvey": "1",
"id": "27",
"fk_curriculumid": "71",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
}
]