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;
Related
I am using netownsoft json.net to serlize an object but its adding string at the start I dont under stand why its doing this.
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
var uri = new Uri(string.Format(url, args));
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
}
return default(T);
}
I am using the following to encode my end point which is hosted in a wcf service.
public string GetWarehouses()
{
DataSet ds = new SqlDa().GetWarehouses();
ds.Tables[0].TableName = "Warehouses";
return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
But the string i am getting back is as such
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
"Warehouses": [
{
"WarehouseID": 13016489,
"Name": "B",
"Description": "Belfast "
},
{
"WarehouseID": 13016647,
"Name": "B",
"Description": "B"
},
{
"WarehouseID": 13815467,
"Name": "Direct Delivery",
"Description": ""
},
{
"WarehouseID": 1008,
"Name": "PW",
"Description": "Postal Way"
},
{
"WarehouseID": 13016234,
"Name": "H",
"Description": "Hospital"
},
{
"WarehouseID": 13016238,
"Name": "MPC",
"Description": "Clinic"
},
{
"WarehouseID": 13029366,
"Name": "O",
"Description": "Outpatient"
},
{
"WarehouseID": 13815466,
"Name": "Returns",
"Description": ""
}
]
}
</string>
As You can see its enclosed it as a string for some reason and don't understand as to why. Is their a way with the data set to make sure that it gets converted into proper json.
If you don't want to modify your server code, you could use regex to extract legal json string from your response.
string content ="your context with xml"
Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
Match match = regex.Match(content);
Response.Write(match.Groups[1].Value);
Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);
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 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
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"
}
]
}
]
I am selecting an IEnumerable<dynamic> from the database using Rob Conery's Massive framework. The structure comes back in a flat format Poco C#. I need to transform the data and output it to a Json array (format show at bottom).
I thought I could do the transform using linq (my unsuccessful effort is shown below):
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.ServiceModel.Web;
....
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
JsonArray returnValue = from item in list
select new JsonObject()
{
Name = item.Test,
Data = new dyamic(){...}...
};
Here is the Json I am trying to generate:
[
{
"id": "1",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "",
"column4 name": "the value"
}
]
},
{
"id": "2",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "the value",
"column4 name": "the value"
}
]
}
]
Here is an example using Json.Net
List<int> list = new List<int>() {1 , 2};
string json = JsonConvert.SerializeObject(
list.Select(x => new{
id = x.ToString(),
title = "title " + x.ToString(),
data = Enumerable.Range(3,2).Select(i=> new {column1=i,column2=i*i})
})
, Newtonsoft.Json.Formatting.Indented
);
Output:
[
{
"id": "1",
"title": "title 1",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
},
{
"id": "2",
"title": "title 2",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
}
]
OK here is what I ended up with it all looks hunky dory:
[WebGet(UriTemplate = "/tools/data/get?tool={tool}&filters={filters}")]
public JsonArray GetData(string tool, string[,] filters)
{
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
IEnumerable<JsonObject> jsonList = from item in list
select new JsonObject()
{
new KeyValuePair<string, JsonValue>("Id", item.Id),
new KeyValuePair<string, JsonValue>("Name", item.Title),
new KeyValuePair<string, JsonValue>("Data", new JsonObject()
{
new KeyValuePair<string, JsonValue>("Product", item.Product),
new KeyValuePair<string, JsonValue>("Suite", item.Suite),
new KeyValuePair<string, JsonValue>("Package", item.Package),
new KeyValuePair<string, JsonValue>("Description", item.Description)
})
};
JsonArray returnValue = new JsonArray(jsonList);
return returnValue;
}