Here is my json returned by php web application:
{"subtotal":475,"tax":47.5,"discount_section":[{"amount":237.5,"name":"test prior for percentage discount
"}],"grand_total_incl_tax":332.5}
I use c# and json.net to decode the abvoe json
var cart = webClient.DownloadString("http://localhost/m1/pos_addToCart.php?pidstr=" + pid_str);
dynamic result = JObject.Parse(cart);
But there is an error on this line:
order_discount_section.Text = result.discount_section;
Error:
Cannot implicitly convert type 'Newtonsoft.Json.Linq.JToken' to 'string'
How to convert this json to String like:
Key1 = Value1
Key2 = Value2
Key3 = Value3
Based upon your supplied json discount_section is a map so it can't be expressed as a string. It's like trying to convert a dictionary to a string or an array to a string.
If you want it as a string representation then adding ToString() after the result.discount_section (i.e. result.discount_section.ToString()) should accomplish that.
Though I would suggest that you either store the data through placeholder values such as:
string name = result.discount_section[0].name (same with amount but float/decimal/double...).
Or if you wanted it as text have it as
text = "Name: " + result.discount_section[0].name
+ "Amount: " + result.discount_section[0].amount.ToString();`
Obviously using a stringbuilder or other tool would be better (such as string.format) but I'll leave that as an 'exercise' to you.
Edit:
The for loop for all of the results.
totalText = ""
for (i = 0; i < result.discount_section.length; i++) {
totalText += "Name: " + result.discount_section[i].name + "Amount: " + result.discount_section[i].amount.ToString() + "\n";
}
Obviously if you wanted an array of strings then you would just build an array then just use i as your string array index as well.
Json.NET provides a correct behaviour.
As from your example string, it can be seen, that discount_section is a json array, or JArray, descendant of JToken after parsing to JObject.
If you want to access inner member of this array, as name for example, you should call it as
order_discount_section.Text = result.discount_section[0].name;
If you want to write the full notation of discount_section as is, you should explicitly call ToString method:
order_discount_section.Text = result.discount_section.ToString();
Although, dealing with dynamics is not useful, while your working with separate service responsing in JSON. It will be better to define a single class, which will handle json values, so you could not only look what json is passing, but to work with it
You may consider working with objects and deserialize using JsonConvert.DeserializeObject. Example:
class Discount
{
public Decimal Amount { get; set; }
public String Name { get; set; }
}
class Response
{
public Decimal Subtotal { get; set; }
public Decimal Tax { get; set; }
public List<Discount> Discount_section { get; set; }
public Grand_total_incl_tax { get; set; }
}
var response = JsonConvert.DeserializeObject<Response>(cart);
This approach is good when object structure is relatively fixed and has the following advantages:
clear structure
relevant errors when you have a type mismatch (JSON -> property)
result.discount_section is collection. you can not set directly to string variable.
try this.
var result= JObject.Parse(cart);
dynamic[] discountSection = result["discount_section"].ToArray<dynamic>();
decimal amount = discountSection[0].amount;
decimal name = discountSection[0].name;
for dictionary
Dictionary<string,decimal> discountDictionary = discountSection.ToDictionary<dynamic, string, decimal>((d) => d.name, (d) => d.amount);
Related
This question already has answers here:
C# to JSON serialization using JSON.Net
(2 answers)
Closed 2 months ago.
I created an exaple to demonstrate the problem. I am trying by string builder create a json but there is one problem when the Model.Code contains the \".
If the model value contains double quote json is not valid.
public class Model
{
public string Name { get; set; }
public string Code { get; set; }
}
List<Model> list = new List<Model>();
list.Add(new Model()
{
Name = "Test1",
Code = "124565123"
});
list.Add(new Model() {
Name = "Test2",
Code= "123 \"45"
});
list.Add(new Model()
{
Name = "Test3",
Code = "456"
});
var sb = new StringBuilder();
sb.Append($"\"item_name\":\"{list[0].Name}\",");
sb.Append($"\"item_id\":\"{list[0].Code}\",");
sb.Append($"\"item_name\":\"{list[1].Name}\",");
sb.Append($"\"item_id\":\"{list[1].Code}\",");
sb.Append($"\"item_name\":\"{list[2].Name}\",");
sb.Append($"\"item_id\":\"{list[2].Code}\",");
return sb.ToString();
Add reference to Newtonsoft Json.NET library and serialize the list to json
string json = JsonConvert.SerializeObject(list);
since you are using StringBuilder, " will be Considered as " in the String value just like below
"item_name":"Test1","item_id":"124565123","item_name":"Test2","item_id":"123 "45","item_name":"Test3","item_id":"456",
so , if you want to Convert it to Json , then Json will not Consider value with Double Quote In Between.
Moreover, backslash with double quote ' \" ' suppose to Escape Special Character while Converting to json
I am not sure that you want to Keep that special Character in you Json string If yes then In My Opinion you should try by placing double backslash \\" and Double Quote before your Special Character. and json will Accept it
ex.
\\"45
This question already has answers here:
What is the correct way to use JSON.NET to parse stream of JSON objects?
(1 answer)
Best ways to split a string with matching curly braces
(2 answers)
Closed 5 years ago.
I am trying to split a c# string that has multiple json strings in it
Example:
{"id":0,"username":"test"}{"id":8,"username":"testuser"}
How can I loop through each json string in its own 'foreach' loop
hi you can do some trikk on invalid json...
string myinvalidJson = "{\"id\":0,\"username\":\"test\"}{\"id\":8,\"username\":\"testuser\"}";
foreach(var item in myinvalidJson.Replace("}{", "}|{").Split('|')) {
...
}
or create valid json and deserialize with newtonsoft
string myinvalidJson = "{\"id\":0,\"username\":\"test\"}{\"id\":8,\"username\":\"testuser\"}";
var validJson = "[" + myinvalidJson.Replace("}{", "},{") + "]";
You may Deserialize it into array of structure type using Newtonsoft.Json
to do this you need to have a string matching an array of JSONs like below:
"[{\"id\":0,\"username\":\"test\"},{\"id\":8,\"username\":\"testuser\"}]"
next lets have strucure type called 'User' like below:
public class User
{
public int Id { get; set; }
public string Username{ get; set; }
}
finally do Deserialize:
string str = "[{\"id\":0,\"username\":\"test\"},{\"id\":8,\"username\":\"testuser\"}]";
User[] res = Newtonsoft.Json.JsonConvert.DeserializeObject<User[]>(str);
Now you are able to do 'foreach' loop on res array.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
I try below code but it only working with one param. ex: {"answer":"Line 1","mark": 1}. I try split json string but it isn't best way.
JObject jObject = JObject.Parse(json );
string asw = jObject["answer"].ToString();
int mark = (int)jObject["mark"];
txtAnswer.Text = asw + "////" + mark + "\n";
This is a very basic JSON question which any number of tutorials could've answered for you.
Is it valid JSON ? No, and JSONLint could've told you that.
How do you read it in ?
First, wrap your JSON in square brackets so it's valid.
Then, define a class to store the records in:
public class Something
{
public string answer { get; set; }
public string mark { get; set; }
}
And finally, use JSON.Net to convert your string into a list of these records.
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
List<Something> records = JsonConvert.DeserializeObject<List<Something>>(json); // JSON.Net
foreach (Something record in records)
{
System.Diagnostics.Trace.WriteLine(string.Format("Answer: {0}, Mark: {1}", record.answer, record.mark));
}
Easy as that.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
Nope, what you've got there doesn't look like valid C# or JSON. Try putting it inside a JSON array, then inside a proper string:
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
(Hope I've got all the escaping right there.)
That's the C# escaped equivalent of the following JSON:
[{"answer":"Line 1","mark": 1}, {"answer":"Line 3","mark": 1}]
Then read up on JObject.Parse()for more info.
Yes it is json format. But There are multiple objects. You are not looping through it. One way could be
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1}\n", item.answer, item.mark);
}
I am trying to Deserialize the string to JSON Object using JsonConvert.DeserializeObject like below:
var str = "{ Value: \"File\",Text: \"OWENS & MINOR INFANT - 2228548\"}";
agreementnodes = JsonConvert.DeserializeObject<List<AgreementNode>>("[" + str + "]");
When the json is converted to an array the properties are alphabetically ordered. Example : Even though Value is first and Text is in the string the properties are displayed like below:
Even in the class declaration, I Value is Firs and Text is second. But when de-serializing, the properties are sorted alphabetically.
[JsonProperty(Order = 9)]
public string Value { get; set; }
[JsonProperty(Order = 10)]
public string Text { get; set; }
Is there any way to retain the order of the properties in the resultant array like I want resultantarray[0] = Value and resultantarray1 = Text?
Nothing wrong with json.net serializer. It's automatically ordered by alphabetical in quickwatch and watch windows. Check System.Web.HttpContext.SystemWebAssembly if you want. It's not a deserialized code.
The ordering of properties are undefined according to the specification. In spite of that the most current ECMAScript (JavaScript) specification requires an ordered format which also enables new cool applications like:
https://cyberphone.github.io/openkeystore/resources/docs/jcs.html#ECMAScript_Compatibility_Mode
I have an array of double which I am sending via JSON to my aspx page.
var array = [] //this array is having double values in it. (48.154176701412744,11.551694869995117),(48.15131361676726,11.551694869995117),(48.15555092529958,11.549291610717773)
var jsonText = JSON.stringify({ list: array });
And following is the method I am passing it to:
public static void Demo(double[] list)
Now how can I access the array being sent and convert it into a string so that I can save it into my database column as string? Because when I accept it as
public static void Demo(string[] list)
It doesn't even accept the JSON object. And when I make the method as:
public static void Demo(double[] list)
It takes the array as [0 0 0].
You can join all doubles with some delimiter:
string.Join(";", list);
However, you should pay attention to using decimal separator. If value will be saved as 1.52;0.4, later you can fail on another machine, or if locale will be changed. I'd decide, what separator I will use always for this case and will convert values to string and back with this separator:
// unfortunately, not tested
var ni = NumberFormatInfo.CurrentInfo; // not sure if you better call Clone() here
ni.NumberDecimalSeparator = ".";
string todatabase = string.Join(";", list.Select(_ => _.ToString(ni)));
To do the opposite operation:
// unfortunately, not tested
var ni = NumberFormatInfo.CurrentInfo; // not sure if you better call Clone() here
ni.NumberDecimalSeparator = ".";
// `str` is read from database value
IEnumerable<double> fromdatabase = str.Split(';').Select(_ => double.Parse(_, ni));
Pay attention to errors handling, this code fragments will fail on bad values (e.g. list was null, str was null, str was containing not-convertible to double values, etc)
JSON.stringfy is itself return a string then why do you need to convert the values to string.You can use JSON.parse('#Html.Raw(jsonText)') to parse the json string on aspx page.This json string can be passed using Session variable.