I have a local json file that I wish to be able to add a new dictionary to the existing array within the file using data entries from a form.
i.e.
turn this:
[
{
"name": "Product1",
"type": "Drink",
"costS": 2.5,
"costB": 2.4,
"amount": "none",
"info": "keep cold"
}
]
into:
[
{
"name": "Product1",
"type": "Drink",
"costS": "2.5",
"costB": "2.4",
"amount": "none",
"info": "keep cold"
}
{"name": "Product2",
"type": "Food",
"costS": "2.8",
"costB": "4",
"amount": "34",
"info": "keep hot"
}
]
where each value comes from a form element ("name" value from txtName, "type" value from txtType, etc).
I have so far tried adapting answers from this post and this post to no avail.
I am very new to c# so it would be much appreciated if answers could be explained to at least a small degree of depth please. Any replies are appreciated however.
You can do like this by using NewtonSoft.Json. first, deserialize the JSON to List<Example> then add the item to this list. and then finally you can serialize the List<Example> to string.
var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.info = "keep hot";
example.amount = "34";
example.costB = "4";
example.costS = "2.8";
example.type = "Food";
list.Add(example);
string output = JsonConvert.SerializeObject(list);
public class Example
{
public string name { get; set; }
public string type { get; set; }
public string costS { get; set; }
public string costB { get; set; }
public string amount { get; set; }
public string info { get; set; }
}
Related
I am working on a C# project where I need to call an API and parse through the JSON response.
The JSON response:
{
"version": "3.9.1",
"data": {
"obj1": {
"version": "1.0.0",
"id": "obj1",
"name": "Object 1",
"title": "Object 1",
"info": {
"info1": 8,
"info2": 4,
"info3": 3
},
"image": {
"full": "Object1.png",
"w": 64,
"h": 64
},
"tags": [
"Tag1",
"Tag2"
]
},
"obj2": {
"version": "1.0.0",
"id": "obj2",
"name": "Object 2",
"title": "Object 2",
"info": {
"info1": 1,
"info2": 6,
"info3": 7
},
"image": {
"full": "Object2.png",
"w": 64,
"h": 64
},
"tags": [
"Tag1",
"Tag6"
]
},
"obj3": {
"version": "1.0.0",
"id": "obj3",
"name": "Object 3",
"title": "Object 3",
"info": {
"info1": 0,
"info2": 1,
"info3": 2
},
"image": {
"full": "Object3.png",
"w": 64,
"h": 64
},
"tags": [
"Tag7",
"Tag8"
]
}
}
}
With this response, I want to loop through all the objects located inside data. The number of objects inside data isn't always the same; it is possible that there will only be one object or ten objects.
The problem I ran into is that I can't loop through the data property because of the following error:
foreach statement cannot operate on variables of type 'Objects' because 'Objects' does not contain a public instance or extension definition for 'GetEnumerator'
I know why I am getting the error, but I can't find a way of fixing my problem.
My code:
MainWindow.xaml.cs
WebRequest request = WebRequest.Create(path);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string ReaderJson = reader.ReadToEnd();
var JsonResponse = JsonConvert.DeserializeObject<Response>(ReaderJson);
foreach (var obj in JsonResponse.data)
{
Console.WriteLine(obj.ToString());
}
JsonParser.cs
public class Response
{
public string version { get; set; }
public Objects data { get; set; }
}
public class Objects
{
public string id { get; set; }
public string name { get; set; }
public string title { get; set; }
public Info info { get; set; }
public Images images { get; set; }
}
public class Info
{
public int info1 { get; set; }
public int info2 { get; set; }
public int info3 { get; set; }
}
public class Images
{
public string full { get; set; }
public int w { get; set; }
public int h { get; set; }
}
How can I loop through all the objects inside data without calling them using obj1, obj2, etc.?
The problem here is that your JSON schema defines a dictionary for data, but your data property returns a single instance of your Objects class.
Data Model
What you want is for your Response class to look something like this:
public class Response
{
public string version { get; set; }
public Dictionary<string, Objects> data { get; set; }
}
Everything else should be fine.
Looping Through Data
Given the above, you can now loop through the data dictionary using something like:
foreach (var obj in JsonResponse.data)
{
Console.WriteLine(obj.Key);
}
Note: When looping through a Dictionary<TKey, TValue>, an enumeration of KeyValuePair<TKey, TValue>s will be returned, with your key (i.e., obj1) in the Key property, and your object in the Value property.
Naming Conventions
Obviously, the name Objects doesn't makes sense here, since it represents a single object, not a collection of objects. I'm keeping it Objects for consistency with your code, but you'll want to give it a singular name. I assume that was just left over from you wanting it to represent a collection.
Get Method is not working... below code display all names or other attributes in richtext box from json using restsharp...there is no error but Ouput is not came help me to solve this...
var client = new RestClient("http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2");
var request = new RestRequest(Method.GET);
var queryResult = client.Execute<List<Detail>>(request).Data;
foreach (var rl in queryResult)
{
richTextBox1.Text = rl.name;
}
public class Detail
{
public string city { get; set; }
public int id { get; set; }
public string Blood { get; set; }
public string name { get; set; }
}
Here is json
{
"Details": [
{
"city": "Londan",
"id": 1,
"Blood": "O+",
"name": "Nicolas"
},
{
"city": "USA",
"id": 2,
"Blood": "A+",
"name": "Jhon"
},
{
"city": "India",
"id": 3,
"Blood": "B-",
"name": "Shiva"
}
]
}
I see two problems:
1) "http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2" - doesn't work
2) If you provided a correct JSON example then you should use "RootObject" here:
client.Execute<List<Detail>>(request).Data;
I'm trying to extract data from JSON but i searched and tried many examples but nothing worked for me. I just want messages node and extract its data to datagridview. Json Object looks like:
{
"limit" : "10",
"offset" : "0",
"size" : "10",
"messages": [{
"address": "+12111",
"body": "hello",
"_id": "4113",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "78454",
"body": "my data",
"_id": "4103",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "7421",
"body": "yes",
"_id": "4101",
"msg_box": "outbox",
"sim_slot": "0"
},
{
"address": "+1235454878",
"body": "balance",
"_id": "4099",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "+123545",
"body": "hello",
"_id": "4098",
"msg_box": "inbox",
"sim_slot": "0"
}
]
}
If you have JSON but don't know how to create corresponding classes that deserialize the JSON into objects, json2csharp.com is helpful. You paste in the JSON and it does its best to infer C# classes from it. You might decide to tweak the classes a little as needed but it gives you a good starting point. Given your JSON it outputs this:
public class Message
{
public string address { get; set; }
public string body { get; set; }
public string _id { get; set; }
public string msg_box { get; set; }
public string sim_slot { get; set; }
}
public class RootObject
{
public string limit { get; set; }
public string offset { get; set; }
public string size { get; set; }
public List<Message> messages { get; set; }
}
Now using Newtonsoft.Json you can do this:
var myObject = JsonConvert.DeserializeObject<RootObject>(stringContainingJson);
A property named _id is a little clunky, so you can change the name and use an attribute to map the the property to the JSON element, like this:
[JsonProperty("_id")]
public string Id { get; set; }
Now you can bind the list of Message to your DataGridView.
myDataGridView.DataSource = myObject.messages;
I have a JSON array with nested objects, representing a menu, as this:
[
[
{
"name": "Item 1",
"id": 1
},
{
"name": "Item 2",
"id": 2,
"children": [
[
{
"name": "Item 21",
"id": 21
}
]
]
},
{
"name": "Item 3",
"id": 3,
"children": [
[
{
"name": "Item 31",
"id": 31,
"children": [
[
{
"name": "Item 311",
"id": 311
},
{
"name": "Item 312",
"id": 312
}
]
]
},
{
"name": "Item 32",
"id": 32
},
...
And I want to deserialize it using JavaScriptSerializer. I have some code as shown below but is not working.
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu>(jsonData);
...
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu[] children { get; set; }
}
The error I get is "The type 'Menu' is not supported to deserialize a matrix".
I would appreciate any help on how to declare the custom object.
Cheers.
Your root object is a 2d jagged array of objects. The properties "children" are also 2d jagged arrays. Thus your Menu class needs to be:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu [][] children { get; set; }
}
And deserialize your JSON as follows:
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu [][]>(jsonData);
Alternatively, if you prefer lists to arrays, do:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public List<List<Menu>> children { get; set; }
}
And then
var objects = serializer.Deserialize<List<List<Menu>>>(jsonData);
Could the issue be that the actual data is an array but you're telling it to expect just one Menu?
I have a big json file. It consist of information of different articles posted on internet. I'm wandering if it's possible to deserialize it object by object. For example, to make a loop and with every iteration a single object from json to be deserialized, then the next one, and so on.
Here are just only two of json file's objects (there are some thousands out there)
[
{
"source": "unimedia",
"title": "some title",
"original_time": "ora: 20:03, 06 dec 2006",
"datetime": "2006-12-06T20:03:00+00:00",
"views": 398,
"comments": 1,
"content": " some content",
"id": "13",
"url": "http://unimedia.info/stiri/-13.html"
},
{
"source": "unimedia",
"title": "some another title",
"original_time": "ora: 20:13, 06 dec 2006",
"datetime": "2006-12-06T20:13:00+00:00",
"views": 173,
"comments": 1,
"content": "some another content",
"id": "19",
"url": "http://unimedia.info/stiri/-19.html"
},
...
]
Here is my class:
class jsonData
{
public string source { get; set; }
public string title { get; set; }
public string original_time { get; set; }
public string datetime { get; set; }
public int views { get; set; }
public int comments { get; set; }
public string content { get; set; }
public int id { get; set; }
public string url { get; set; }
}
Can anybody help me with that ?
You just need to use use Newtonsoft.Json
Newtonsoft Json
string json = File.ReadAllText(PathFile);
jsonData obj = JsonConvert.DeserializeObject<jsonData>(json);