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);
}
Related
This question already has answers here:
How to handle both a single item and an array for the same property using JSON.net
(9 answers)
Closed 2 years ago.
I have a JSON response like the following
{
"result": "success",
"totalresults": "100",
"items": {
"item": [
{
"id": "5812",
"lineitems": {
"lineitem": [
{
"type": "product",
"status": "Active"
}
]
}
},
{
"id": "5",
"lineitems": []
}
]
}
}
While trying to deserialize this with a specific type it throws exception because of the lineitems property. lineitems is an empty array for one item and for the other item it has a property lineitem with an array. I don't have control over this JSON data. Please suggest me how to deserialize this without any error.
Using lineitems as object would help me to deserialize the JSON but then I'll end up having 2 different types in the object field which is not gonna help me either.
If you are sure about "lineitems", You can do the replace policy. Once you get the JSON string from API, Do a condition based replace
json = json.Replace("lineitems: []", "lineitems: null");
Once you do it, Your JSON will be standardized. Then you can do desterilize.
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 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.
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.
i got some problem when i generate .json file from spring .json ,and i got this format
{ "models": [
{
"id":1,
"modelName":"dfdsf",
"created":{
"userFullname":"demo",
"time":"150301",
"date":"20110208",
"userId":"123"
},
"remark":"dsfdf",
"updated":"~unique-id~1"
},
{
"id":2,
"modelName":"test",
"created":{
"userFullname":"test",
"time":"150301",
"date":"20110210",
"userId":"124"
},
"remark":"test",
"updated":{
"userFullname":"test",
"time":"150301",
"date":"20110209",
"userId":"test"
}
}
]}
first time i used JObject Parse for convert
JObject job = JObject.Parse(fullJson);
and the other hand i used jtoken to focus "models"
JToken jDetail = job["models"];
but the problem is {[{ xxx }]} it look like jarray i don't have any idea to convert it
i ever use JArray, JsonTextReader but it doesn't work.
could suggestion some? because if i pass this ll i set some value to object.
thank you for every idea.
string fullJson = File.ReadAllText("TextFile1.txt"); // for brevity
var job = JObject.Parse(fullJson);
var models = job.Value<JArray>("models");
Console.WriteLine(models[0]);
result:
{
"id": 1,
"modelName": "dfdsf",
"created": {
"userFullname": "demo",
"time": "150301",
"date": "20110208",
"userId": "123"
},
"remark": "dsfdf",
"updated": "~unique-id~1"
}