Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have the following json string:
{
"data":
{
"id": "1",
"city": "London"
},
"cityDetails":
{
"_id": "1",
"location": "UK",
"th": 0,
"title": "Default Group",
}
},
"limit": 0.60451203584671021,
"_id": "1234"
}
How can I extract the the 'city' name from the 'data' section of the JSON string using Newtonsoft.Json in C#.
Try
// load your json here
var obj = JObject.Parse(#"{
""data"":
{
""id"": ""1"",
""city"": ""London""
},
""_id"": ""1234""
}");
// get the city
var city = (string)obj.SelectToken("data.city");
You need to update the selected-token path if the JSON you provided is part of/inside another.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
How can I update "UserPhoneNumber" property value in "Data" property alone from this object. I have done only to change value of property and not nested object.
var updateProfile = generalSettingResponse.Select(x => settingsList.ContainsKey(x.Key) ? settingsList.First(y => y.Key.ToLower() == x.Key) : x);
sample json object:
{
"Name": "John",
"SNo": "1234",
"Data": {
"UserPhoneNumber": "9102287287",
"UserProfileName": "John"
}
}
If you want to change property of json object,here is a demo:
SampleJObject:
{ "Name": "John", "SNo": "1234", "Data": { "UserPhoneNumber": "9102287287", "UserProfileName": "John" } }
Use the following code,the property UserPhoneNumber will be changed:
SampleJObject["Data"]["UserPhoneNumber"] = "0123456789";
result:
You cannot use this:
updateProfile.Data.UserPhoneNumber = "+18888888888";
That will only work if the setters in the class are public.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My problem is that I need to parse json to another json format, I need to do that recursive. I have been tried diferents way but any works fine for me.
I would like to know more ways for test.
Thanks!
{
"items": {
"itemName": {
"type": "type",
"properties": {
"item1": {
"type": 1,
"isValid": true
},
"item2": {
"type": 1,
"isValid": true
}
}
}
}
}
And I need to make this
{
"items":{
"item1": 1,
"item2": 1
}
}
You can try with JToken to read the JSON and JsonConvert to convert the object to desired JSON
using (StreamReader r = new StreamReader(filepath))
{
var inputString = r.ReadToEnd();
JToken outer = JToken.Parse(inputString);
JObject inner = outer["items"]["itemName"]["properties"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
var items = new ExpandoObject() as IDictionary<string, Object>;
foreach (string k in keys)
{
items.Add(k, Convert.ToInt32(outer["items"]["itemName"]["properties"][k]["type"]));
}
Console.WriteLine(JsonConvert.SerializeObject(new { items = items }));
}
output
{"items":{"item1":1,"item2":2}}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Can you create brackets using dynamic json without the name of the list/array appearing in the json string? Otherwise I will need to rewrite entire section.
The problem is i haven't figured out how to create brackets in dymanic json without having a name that comes before it. In my json string, values will have a parent bracket wrapping all its entries, then a bracket wrapping the timestamp and another bracket wrapping the books. The brackets wrapping timestamp & books should not have names appearing in front of them.
Using this link, I got very close to the format I want but I'm missing the bracket separation for time and the remaining entries.
sample code:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
midObject.value.Add(record);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();
current output:
{
"records": [
{
"value": [
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
},
{
"Title": "Book2",
"Author": "author1"
},
{
"Title": "Book1"
"Author": "author1"
"Notes": "testtest"
}
]
}
]
}
desired output:
{
"records": [
{
"value": [
[ ------->bracket wrapping timestamp
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
}
] ------->bracket wrapping timestamp
,
[ ------->bracket wrapping books
{
"Title": "Book2",
"Artist": "artist1"
},
{
"Title": "Book1"
"Artist": "artist1"
"Notes": "testtest"
}
] ------->bracket wrapping books
]
}
]
}
edit: May have oversimplified but books section has 20+ fields. Each json string will only have one timestamp but can have 100's -1,000's of books per request.
edit2: title / clarification on the main question.
As far as I can see, you just need to add another array for all the records:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic arrayrecord = new JArray();
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
arrayrecord.Add(record);
midObject.value.Add(arrayrecord);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Already checked this post but that did not solve my situation : Parsing a JSON array using Json.Net
I have a API response which returns me a JSON array, like the following :
{
"status": {
"code": "200",
"description": "OK"
},
"response": [{
"weId": "1",
"weName": "env1"
},{
"weId": "2",
"weName": "env2"
},{
"weId": "3",
"weName": "env3"
}]
}
Here's my question :
This array might return more than 2 values.
What i mean is like this :
{
"response": [{
"weId": "1",
"weName": "env1",
"otherAttribute1": "otherValue1",
"otherAttribute2": "otherValue2",
"otherAttribute3": "otherValue3"
}]
}
How am I able to dynamically parse a JSON array, which has an unknown dimension ?
Thanks in advance.
Json.Net can dynamically parse into a JObject.
var unParsed = #"{
""response"": [{
""weId"": ""1"",
""weName"": ""env1"",
""otherAttribute1"": ""otherValue1"",
""otherAttribute2"": ""otherValue2"",
""otherAttribute3"": ""otherValue3""
}]
}";
dynamic d = JObject.Parse(unParsed);
Console.WriteLine(d.response[0].weId);
Console.WriteLine(d.response[0].otherAttribute1);
foreach (var r in d.response)
{
foreach (var prop in r.Properties())
{
Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
}
}
Now, that being said, you may not need to do it dynamically. If you have a known set of optional parameters, you can deserialize it into a strongly typed object and anything missing will just be the default value (0 for ints, null for classes, etc), as in the answer below:
public static void JsonParsing()
{
var unParsed = #"{
""status"": {
""code"": ""200"",
""description"": ""OK""
},
""response"": [{
""weId"": ""1"",
""weName"": ""env1""
},{
""weId"": ""2"",
""weName"": ""env2"",
""otherAttribute1"": ""value1"",
""otherAttribute2"": ""value2"",
""otherAttribute3"": ""value3""
},{
""weId"": ""3"",
""weName"": ""env3""
}]
}";
var parsed = JsonConvert.DeserializeObject<Rootobject>(unParsed);
Console.WriteLine(parsed.Response[0].OtherAttribute1); // writes a "" since it's null
Console.WriteLine(parsed.Response[1].OtherAttribute1); // writes "Value1"
Console.WriteLine(parsed);
}
This question already has answers here:
How to ignore a property in class if null, using json.net
(17 answers)
Closed 5 years ago.
I have JSON that I am getting back that potentially gets back nulls as part of the values. How can I, or is there even a way, to exclude those nulls from the collection?
{
"id": "5551212",
"from": {
"name": "Message creator",
"start_time": "2011-10-21T22:00:00",
"end_time": "2011-10-23T17:00:00",
"location": "area 51",
"id": "2121212122"
},
"to": {
"data": [
{
"name": "Jay-Z",
"id": "77777"
},
{
"name": "Bill Murray",
"id": "88888"
},
null,
{
"name": "Anthony Hopkins",
"id": "99999"
}
]
},
"message": "Some message from somewhere",
"updated_time": "2011-09-19T23:53:51+0000",
"unread": 1,
"unseen": 0
}
Notice between Bill Murray and Anthony Hopkins the null that is returned. Thanks.
You can simply decorate properties/fields that can be null with
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
For more info on how to reduce json size: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx
I would use convert method to get an XML string.
// jsonString is populated from your....
XmlNode xmlNode = JsonConvert.DeserializeXmlNode(jsonString);
The null value in XML would be like:
...<data></data>...
which can be easily removed by string replacement or XML filtering.