I've merged two JSON response into a single object:
This is how I did it
string peter= "\"peter\"";
string james= "\"james\"";
var jsonStringJames = await jsonStringJames .Content.ReadAsStringAsync();
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
return Ok("{" + peter+ ":" + jsonStringPeter + ","+ james+ ":" + jsonStringJames + "}");
my JSON looks as follow:
{
"peter": {
"total": 1,
"result": [
{
"value": "James Bond",
"OWNER":"peter" <--- add this
}
]
},
"james": {
"count": 2,
"next": null,
"previous": null,
"results": [{
"gender": "male"
"OWNER":"james" <--- add this
}]
}
}
How do I add the object name as a key? server-side?
Thanks alot!
try this using ´JObject´
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
var objJson = JObject.Parse(jsonStringPeter);
objJson["result"][0]["OWNER"] = "peter";
var jsonStringJames = await jsonStringJames.Content.ReadAsStringAsync();
var objJson2 = JObject.Parse(jsonStringJames);
objJson2["OWNER"] = "james";
Related
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
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 have a requirement to delete the data inside JSON file. I have tried so many way but it is not deleting the data. I have also tried this example.
Remove JSON objects from a large file
But in above example they are passing a jsonstring but I have a jobject type of data.
My JSON File is as following.
{
"id": 123,
"name": "Pankaj Kumar",
"address": {
"street": "El Camino Real",
"city": "San Jose",
"zipcode": 95014
},
"experiences": [
{
"companyid": 1,
"companyname": "abc1"
},
{
"companyid": 20,
"companyname": "Genpact Headstrong"
},
{
"companyid": 71,
"companyname": "new company"
},
{
"companyid": 77,
"companyname": "Mind Tree LTD"
},
{
"companyid": 89,
"companyname": "TCS"
},
{
"companyid": 22,
"companyname": "Hello World LTD"
}
],
"phoneNumber": 9988664422,
"role": "Developer"
}
I want to delete company based on companyid.
I have tried following code to delete based on company id.
private void DeleteCompany() {
var json = File.ReadAllText(jsonFile);
try {
var jObject = JObject.Parse(json);
JArray experiencesArrary = (JArray) jObject["experiences"];
Console.Write("Enter Company ID to Delete Company : ");
var companyId = Convert.ToInt32(Console.ReadLine());
if (companyId > 0) {
var companyName = string.Empty;
foreach(var company in experiencesArrary.Where(obj => obj["companyid"].Value < int > () == companyId)) {
companyName = Convert.ToString(company["companyname"]);
}
var companyToDeleted = "{ 'id': " + companyId + ", 'companyname': '" + companyName + "'}";
experiencesArrary.Remove(companyToDeleted);
jObject["experiences"] = experiencesArrary;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(jsonFile, output);
} else {
Console.Write("Invalid Company ID, Try Again!");
UpdateCompany();
}
} catch (Exception) {
throw;
}
}
Please suggest or modify my code which delete the data.
There is no need for creating deleteObject like you are doing, you are very close to solution.You can simply find your object like this and remove.
var companyToDeleted = experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId).ToList();
foreach (var item in companyToDeleted)
{
experiencesArrary.Remove(item);
}
Update
var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);
experiencesArrary.Remove(companyToDeleted);
Suppose i have
Json1:
[
{
"key":"1",
"val2":"5",
"val3":"short",
"val4":"pant",
"val5":"blue",
},
{
"key":"2",
"val2":"6",
"val3":"long",
"val4":"shirt",
"val5":"red",
}
]
And I have Json2:
[
{
"key":"1",
"qty":"3"
},
{
"key":"2",
"qty":"6",
}
]
I would like to have the following results
Json3:
[
{
"key":"1",
"val2":"5",
"val3":"short",
"val4":"pant",
"val5":"blue",
"qty":"3"
},
{
"key":"2",
"val2":"6",
"val3":"long",
"val4":"shirt",
"val5":"red",
"qty":"6"
}
]
is there a way to combine using a key in my case I would want to use the "key" as the key to know what qty to place where.
I'm trying to achieve a similar effect of an inner join to combine them that way.
Thanks,
var json1 = '[' +
'{ "key":"1" , "val2":"5", "val3":"short", "val4":"pant","val5":"blue" }, ' +
'{ "key":"2", "val2":"6", "val4":"shirt", "val5":"red" } ]';
var json2 = '[' +
'{ "key":"1", "qty":"3"}, ' +
'{ "key":"2", "qty":"6" } ]';
var obj1 = JSON.parse(json1);
var obj2 = JSON.parse(json2);
for(var i in obj1) {
if(obj1[i].key === obj2[i].key) {
obj1[i].qty = obj2[i].qty;
}
}
console.log(obj1);
Using Json.net's merge method:
var json1 = JArray.Parse(#"[
{
""key"":""1"",
""val2"":""5"",
""val3"":""short"",
""val4"":""pant"",
""val5"":""blue"",
},
{
""key"":""2"",
""val2"":""6"",
""val3"":""long"",
""val4"":""shirt"",
""val5"":""red"",
}
]");
var json2 = JArray.Parse(#"[
{
""key"":""1"",
""qty"":""3""
},
{
""key"":""2"",
""qty"":""6"",
}
]");
json1.Merge(json2, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Merge
});
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"
}
]
}
]