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.
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:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
Below is my JSON information where you can notice that there is not any key defined.
{"KOA": {"test.jpg": "xyz.com/images/test.jpg"}}
I am Looking the Output like:
string _imgName= ms-koa-acazia-ceramic.jpg
string _imgUrl= xyz.com/images/test.jpg
"KOA" is also a dynamic value it can be changed so I can not fix it.
One approach you can use to achieve this is to use dictionaries to deserialize the JSON object
const string jsonString = "{\"KOA\": { \"test.jpg\": \"xyz.com / images / test.jpg\"}}";
var jsonObject = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, string>>>(jsonString);
string firstKey = jsonObject.Keys.First();
string _imgName = jsonObject[firstKey].Keys.First();
string _imgUrl = jsonObject[firstKey].Values.First();
This question already has answers here:
How do i split a String into multiple values?
(5 answers)
Closed 3 years ago.
Not entirely sure the following code is going to help many people, but here goes
try
{
uvConnect = UniObjects.OpenSession(serverId, sUser, sPass, sAcct, "uvcs");
// Open Movie File
UniFile uvFile = uvConnect.CreateUniFile("MOVIES");
UniDynArray movieRec = uvFile.Read(txtMovieId.Text);
string sMovieData = movieRec.StringValue;
MessageBox.Show(sMovieData);
}
sMovieData contains a single string of the entire record retrieve from MOVIES file, each field is deliminated by a char(253) character in the database I am using.
Is there a function/method/etc to convert the string to an array using char(253) as a value deliminator
Something like this should work:
string[] fields = sMovieData.Split((char)253);
Try this... string[] arrayValues = "stringToConvertToArray".Split((char)253);
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);
}
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);