how to post array json .net? - c#

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 });

Related

json object data accessing via index

I have following json object of array structure.I am trying to retrieve certain elements from array of objects
{
"data": [
{
"_id": "5b62dc6ebef986403db8aafd",
"name": "smitha vijaya",
"designation": "account management",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
},
{
"_id": "5b62dd17bef986403db8ab90",
"name": "JIKKU VARGHESE",
"designation": "SUPERVISING OPERATIONS MANAGER",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
},
{
"_id": "5b62dd76bef986403db8abe3",
"name": "SUJEETH NAIR",
"designation": "MENA AMS",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "30"
},
{
"_id": "5b62ddb1bef986403db8ac13",
"name": "GIRISH KN",
"designation": "MENA AMS",
"projects": {
"project1": "description1",
"project2": "description2"
},
"age": "27"
}
]
}
I am using following c# code to extract ist name (smitha)
JsonData jsonvale = JsonMapper.ToObject( jsonString);
Name = jsonvale["data"][0]["name"].ToString();
print (name);
how can i acces other elements like name jikku and so on?
You could iterate using a for loop:
for(int i = 0; i < jsonvale.length; i++) {
JsonData jsonvale = JsonMapper.ToObject(jsonString);
Name = jsonvale["data"][i]["name"].ToString();
print(name);
}
You can iterate it over your json array like following:
JsonData jsonvale = JsonMapper.ToObject( jsonString);
for (var i=0; i<jsonvale.length; i++){
print(jsonvale["data"][i]["name"].ToString());
}
Just deserialize this json in List() and then you can access all data from this list without loops, and when you do not need this list anymore, you can destroy it. See this example https://github.com/IonCojucovschi/JsonDeserializeGenericForm

c# can't build json hierarchy correctly using newtonsoft

I looked at this SO question but it doesn't address my needs: Build JSON Hierarchy from Structured Data
The problem: When trying to build the json, the nesting of children isn't done correctly. The children property should contain 1 or more name array items like this:
"children": [{
"name": "XXX - Level XXX",
...instead it is generated as:
"children": []
Here's a dotnet fiddle with more code details:
I'm trying to build the tree by using json.net .Last to grab the last child and then add a JObject to that child but that isn't working out too well for me.
The main data structure used to build the json :
Dictionary<int, Industry>();
The desired json structure should be:
{
"name": "XX Level XX",
"children": [{
"name": "XXX - Level XXX",
"children": [{
"name": "XXXX - Level XXXX",
"children": [{
"name": "XXXXX - Level XXXXX",
"children": [{
"name": "XXXXXX - Level XXXXXX"
}]
}]
}]
}]
}
The actual output is:
{
"name": "XX-Level XX",
"children": [{
"name": "XXX-Level XXX",
"children": []
}, {
"name": "XXXX-Level XXXX",
"children": []
}, {
"name": "XXXXX-Level XXXXX",
"children": []
}, {
"name": "XXXXXX-Level XXXXXX",
"children": []
}
]
}
Here's the code that builds the json:
dynamic relationship = new JObject();
relationship.name = relationships[0].Industries[1].Name;
relationship.children = new JArray();
var lftIndustries = relationships[0].Industries.Where(k => k.Key > 1);
foreach (var item in lftIndustries)
{
//not good enough, need to get deepest, empty "children" node
// and add "industry" to it
var node = ((JContainer)relationship).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
}
json = relationship.ToString();
I thought that using json.net .Last and .Next would be the answer.
try this in your foreach loop and tell me if it is whats youre looking for:
JToken currentContainer = null;
foreach (var item in lftIndustries)
{
//not good enough, need to get deepest, empty "children" node
// and add "industry" to it
if (currentContainer != null)
{
var node = ((JContainer)currentContainer).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
currentContainer = industry;
}
else
{
var node = ((JContainer)relationship).Last;
var childArray = (JArray)((JContainer) node).Last;
var industry = new JObject(new JProperty("name", item.Value.Name), new JProperty("children", new JArray()));
childArray.Add(industry);
currentContainer = industry;
}
}
The result is this:
{
"name": "XX-Level XX",
"children": [
{
"name": "XXX-Level XXX",
"children": [
{
"name": "XXXX-Level XXXX",
"children": [
{
"name": "XXXXX-Level XXXXX",
"children": [
{
"name": "XXXXXX-Level XXXXXX",
"children": []
}
]
}
]
}
]
}
]
}
Heres the fiddle: https://dotnetfiddle.net/1yzTGU

'Newtonsoft.Json.Linq.JArray' to 'System.Web.UI.WebControls.ListItemCollection'

I have a Json file as shown below. I want to convert only the option node in the JSON file into a C# ListItemCollection object
ASP.net File:
var path = Server.MapPath(#"~/json.json");
using (StreamReader r = new StreamReader(path,false))
{
string json = r.ReadToEnd();
dynamic arr = JsonConvert.DeserializeObject(json);
ListItemCollection licRB = new ListItemCollection();
licRB = arr.AnswerRadioButton.option;<<-- run time error is produced here
}
JSON File:
{ "FormTitle": "This is Form Title from JSON",
"TitleQuestion1": "This is the Title of Question 1",
"TextQuestion1": "1- This is the text of Quextion Number 1",
"AnswerRadioButton": {
"visible": "true",
"title": "Radio Button Title",
"FieldsetRBStyle": { "border": "1px" },
"option" : [
{
"text": "text1",
"value": "v1",
"checked": "false"
},
{
"text": "text2",
"value": "v2",
"checked": "true"
},
{
"text": "text3",
"value": "v3",
"checked": "false"
},
{
"text": "text4",
"value": "v4",
"checked": "true"
}
] }}
Assuming that you have the required classes (e.g. using this tool) you can access the options like this:
var test = JsonConvert.DeserializeObject<RootObject>(json);
var options = test.AnswerRadioButton.option;

Newtonsoft JSON - create JArray in JArray

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"
}
]
}
]

How to convert the following list to a dictionary?

The following code:
var data = _context.People.ToList(); //_context is my DataContext.
produces the result:
[{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }]
but, I want it to be a dictionary, so something like:
{ "xldata" : [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }] }
I got it to work by doing:
Dictionary<string,List<People>> vals = new Dictionary<string, List<People>>();
vals.Add("xldata", people);
but, my dictionary's value is System.Object[] instead of the people
The purpose of this is to export data, so when I get to this line:
var people = jss.Deserialize<List<People>>(args["xldata"]);
args["xldata"] is `System.Object[]` and it says `Invalid JSON primitive`.
Here is the script is supposed to export the data to excel:
$.post(urlContent + exportHandlerPath, Json, function(data) {
var viewData = {};
viewData.xldata = JSON.stringify(data);
html = ich.excelExportTemplate(viewData);
$excelExportContainer.html(html);
var input = $excelExportContainer.find('input#excelExportHiddenField');
input.val(viewData.xldata);
var $excelForm = $('#excelExportForm');
$excelForm.attr('action', '/People/ExportToExcel/');
$excelForm.submit();
}
Apparently your args["xldata"] does not contain a json string like [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }], but something returned by a .net object .ToString().
With JavaScriptSerializer.Deserialize you can only deserialize json represenations.

Categories

Resources