How to convert sub-array to json. I have tried
JArray _extra = JArray.Parse(extra.OrderOfferObject);
if (_extra.Count() > 0)
return Ok(new
{
Data = _extra, // ---
}
So it did convert the string to JArray but skip the inner array. Here's the response:
Data: [{ Category: "Chicken Rice",
Ingredients: "[{ExtraQuantity=1, ExtraPrice=11.99, ExtraTitle=Regular},
{ExtraQuantity=1, ExtraPrice=0.0, ExtraTitle=Stuffed Cheese},
{ExtraQuantity=1, ExtraPrice=0.0, ExtraTitle=Sauce BBQ}}]"}]
How do i convert the inner one, thanks.
Update
var extra = (from orderOffer in extraEntities.ORDER_OFFER
where orderOffer.OrderOfferId == orderOfferId
select new
{
orderOffer.OrderOfferObject
}).FirstOrDefault();
Where OrderOfferObject is an array of string type having nested array.I tried JArray.parse to convert to JsonArray. Alas! it did not convert the nested array, as you can see in response.
Seems like your nested string is in a wrong format.
Currently your string object is this:
{ExtraQuantity=1, ExtraPrice=11.99, ExtraTitle=Regular}
It should be like this:
{ExtraQuantity: 1, ExtraPrice: 11.99, ExtraTitle: Regular}
Once your object is fine. JArray. Parse () only will do the trick.
Related
I need to generate XMLDocument from JObjects, and I'm trying to figure out how to make an array of JObjects convert properly to XML. This is the section giving me trouble:
JObject billsegment = new JObject
{
{"ext_bill_id", bill.ExternalBillID},
{"cust", new JObject
{
{"typ_id_cust","1"},
{"id_cust", bill.CustomerID}
}
},
// This element is giving me trouble
{"bill_line_list", GetBillLines(bill.LineData)}
};
The problem: The resulting XML is:
<bill_line_list>
<bill_line>
<line_no>1</line_no>
<id_elm_bill>06159</id_elm_bill>
</bill_line>
</bill_line_list>
<bill_line_list>
<bill_line>
<line_no>2</line_no>
<id_elm_bill>05432</id_elm_bill>
</bill_line>
</bill_line_list>
Notice there are two <bill_line_list> elements, of which I only want one. I want the result to be:
<bill_line_list>
<bill_line>
<line_no>1</line_no>
<id_elm_bill>06159</id_elm_bill>
</bill_line>
<bill_line>
<line_no>2</line_no>
<id_elm_bill>05432</id_elm_bill>
</bill_line>
</bill_line_list>
My GetBillLines() method returns a JArray, which I formulate like this:
JArray GetBillLines(dynamic lineData)
{
int num_lines = lineData.NumLines;
JArray lines = new JArray();
for (int lineNum = 1; lineNum < num_lines+1; lineNum++)
{
JObject line = new JObject
{
{"line_no", lineNum },
{"id_elm_bill", billData.Lines[lineNum].billCode},
};
lines.Add(new JObject
{
{"bill_line", line}
});
}
return lines;
}
What I've tried: I've tried making the return type of my GetBillLines() to JArray and JToken[], and I've tried returning the JArray with .ToArray(). Also, in my JObject billsegment I've tried changing the last line to
JToken.FromObject(GetBillLines(bill.LineData))
and other various things. I'm wondering why it creates two <bill_line_list>s, since when I create the object I am only adding ONE bill_line_list property, and setting the JToken as an array.
I know that you can force Json arrays when serializing from XML (via json:Array='true'), is there an equivalent the other way around?
I have a Json string like below and this is only a small snippet. The number in quotation marks is a Unix Time which i will need to use to iterate over each object.
{
"result": {
"1534860000": [
"1534860000",
19,
41
],
"1534863600": [
"1534863600",
11,
16
],
"1534867200": [
"1534867200",
2,
5
]
}
}
But when I attempt to extract the data in the arrays I get an error:
System.InvalidOperationException: 'Cannot access child value on Newtonsoft.Json.Linq.JProperty.'
Code:
JObject jsonObj = JObject.Parse(response);
string unixTime = Helpers.ConvertToUnix(yesterday.AddHours(hour)).ToString();
foreach (var obj in jsonObj["result"])
{
var array = obj[unixTime]; //here is where the error occurs
}
Anyone able to shed some light on what I am missing?
If we simplify your example code a little to remove the unixTime element (let's just hardcode it for now), we end up with this:
JObject jsonObj = JObject.Parse(response);
string unixTime = "1534860000";
At this stage, we have jsonObj which refers to the root of the JSON object and has a single property of result. Repeating your foreach here for context:
foreach (var obj in jsonObj["result"])
{
var array = obj[unixTime]; //here is where the error occurs
}
You end up with obj referring to the JSON path of result.1534860000. The problem is you're then looking for a property 1534860000 at this JSON path (result.1534860000.1534860000), which does not exist.
You can just get the value directly, like so:
var array = obj["result"][unixTime]
Of course, this requires some error-checking for ensuring the path exists, etc, but it demonstrates the point.
After some help from Kirk Larkin I thought I would post a code snippet up.
JObject jsonObj = JObject.Parse(response);
int hour = 0;
string unixTime = Helpers.ConvertToUnix(yesterday.AddHours(hour)).ToString();
var array = jsonObj["result"][unixTime];
It now returns the contents of the array.
I am new to c# don't know how to get a JSON array of array stored in a 2d array. I am having a JSON file with students marks like
[
[10,5,4],
[9,6,3]
]
and out of this I am using this code but getting error out at JArray
JArray a = JArray.Parse(json);
I have tried some other approaches as well but nothing helped basically what I want to do is want to create a boolean 2D array which will be populated on the basis of the above JSON record and for that purpose I want to populate the array with JSON content.
With the following valid JSON
{ "data" : [
[10,5,4],
[9,6,3]
]
}
The following class was used to hold the parsed data
public class RootObject {
public IList<IList<int>> data { get; set; }
}
which can be parsed using Json.Net
var root = JsonConvert.DeserializeObject<RoootObject>(json);
and the content accessed
var x1 = root.data[0][1]; // 5
var x2 = root.data[1][1]; // 6
I am trying to Convert Json to DataTable. I found success when converting jsonArray to DataTable. However when converting a json string(below):
var r = {'ASSOCIATION_ID':61.0,'DESCRIPTION':'fssESTf64 - false','ACTIVE':true,'MODEL_TYPE':'0','SEARCH_TYPE':'false','CREATED_BY':'1090323','CREATED_DATE':'2015-09-17T14:41:20','LAST_UPDATED_BY':'1090323','LAST_UPDATED_DATE':'2016-02-26T15:55:54'}
I get an error as {"Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1."}
My code is simple:
DataTable a = JsonConvert.DeserializeObject<DataTable>(r);
Please assist.
Your root JSON container is an object (an unordered collection of comma-separated key/value pairs surrounded by braces - { and }). Json.NET serializes a DataTable as an array of objects (an ordered collection of comma-separated tokens surrounded by square brackets [ and ]), with one array entry for each row, as is shown in Serialize a DataSet. I.e. the following can be deserialized as a data table:
[
{
"ASSOCIATION_ID": 61.0,
"DESCRIPTION": "fssESTf64 - false",
"ACTIVE": true,
"MODEL_TYPE": "0",
"SEARCH_TYPE": "false",
"CREATED_BY": "1090323",
"CREATED_DATE": "2015-09-17T14:41:20",
"LAST_UPDATED_BY": "1090323",
"LAST_UPDATED_DATE": "2016-02-26T15:55:54"
}
]
Thus your JSON cannot be mapped automatically to a DataTable by Json.NET.
If you want, you could deserialize your JSON object as a DataTable with one row. To do that, load it into an intermediate JToken, check if it's an object instead of an array, and if so, wrap it in an array, then deserialize:
var token = JToken.Parse(r);
if (token.Type == JTokenType.Object)
token = new JArray(token);
var a = token.ToObject<DataTable>();
I'm having trouble converting a string of json facebook graph api, I used the facebook C# and json.Net.
But at conversion time it returns this error: Name can not begin with the '0 'character, hexadecimal value 0x30.
This is the code:
dynamic result = await _fb.GetTaskAsync ("me / feed");
FBxml JsonConvert.DeserializeXNode string = (result.ToString ()). ToString ();
It looks like there is a problem with portion of the json string as mentioned below (taken from your link http://jsfiddle.net/btripoloni/PaLC2/)
"story_tags": {
"0": [{
"id": "100000866891334",
"name": "Bruno Tripoloni",
"offset": 0,
"length": 15,
"type": "user"}]
},
Json cannot create class that begins with a numeric value such as '0'. Try creating the classes using the link http://json2csharp.com/ you will get an idea.
To solve this problem you can create a dynamic object and go through each properties OR create a JsonConverter and write your code in the ReadJson to convert the "0" to a meaningful name. May be this can help you http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization
If this is not your problem then update the question with more information like class structure of FBxml, call stack of the exception (from which line of the json code is throwing the exception), Json version etc.
As keyr says, the problem is with those JSON properties that have numeric names. In XML names can contain numeric characters but cannot begin with one: XML (see the Well-formedness and error-handling section).
My idea was to recursively parse the JSON with JSON.Net, replacing properties that had numeric names:
var jsonObject = JObject.Parse(json);
foreach (var obj in jsonObject)
{
Process(obj.Value);
}
XDocument document = JsonConvert.DeserializeXNode(jsonObject.ToString());
....
private static void Process(JToken jToken)
{
if (jToken.Type == JTokenType.Property)
{
JProperty property = jToken as JProperty;
int value;
if (int.TryParse(property.Name, out value))
{
JToken token = new JProperty("_" + property.Name, property.Value);
jToken.Replace(token);
}
}
if (jToken.HasValues)
{
//foreach won't work here as the call to jToken.Replace(token) above
//results in the collection modifed error.
for(int i = 0; i < jToken.Values().Count(); i++)
{
JToken obj = jToken.Values().ElementAt(i);
Process(obj);
}
}
}
This seemed to work well, prefixing numeric names with _. At this line:
XDocument document = JsonConvert.DeserializeXNode(jsonObject.ToString());
it crashed with an error saying that invalid/not well formed XML had been created. I don't have the actual error with me, but you can run the above code to replicate it.
I think from here you may need to revisit converting the JSON to XML in the first place. Is this a specific requirement?