c# model when one property is json - c#

i have a simple data
[{
"rowNumber": 1,
"name": "aaa",
"results": "json string data"
},
{
"rowNumber": 2,
"name": "bbb",
"results": "json string data"
}],
then i have a class
public class CeremonySaloonSaloonItems
{
public long? saloonId { get; set; }
public string saloonName { get; set; }
public string results{ get; set; }
}
where results is another list that here is json
then and after i import data i loop all data and deserialize results.
but i think must be a better way to get data deserialized.

And add this lines of code
JavaScriptSerializer js = new JavaScriptSerializer();
CeremonySaloonSaloonItems Ceremony = js.Deserialize<CeremonySaloonSaloonItems>(jsonData);
string name = Ceremony.Name;
string description = Ceremony.Description;
use javascript Serializer and give your class as a list generic type.
Using JSONCONVERT:
Import newtonsoft json from nuget package manager.
And this code.
CeremonySaloonSaloonItems Ceremony = JsonConvert.DeserializeObject<CeremonySaloonSaloonItems>(jsondata);
Response.Write(Ceremony.Name);
Using Json .Net and Foreach
var jsonObj = new JavaScriptSerializer().Deserialize<CeremonySaloonSaloonItems>(json);
foreach (var obj in jsonObj.entity)
{
Console.WriteLine(obj.name);
}

Related

How to query into a JSON getting using LINQ?

JSON
{
"count": 3,
"value": [
{
"id": "AAAAAAAAAAAAA",
"description": "test1",
"name": "name1"
},
{
"id": "BBBBBBBBBB",
"description": "test2",
"name": "name2"
},
{
"id": "CCCCCCCCCCCC",
"description": "test3",
"name": "name3"
}
]
}
I have a code in my solution retrieving from a LIST api and giving the JSON above.
How can I use a LINQ to retrieve specific values? (e.g) I need to select name1 and I will get the id,description,name values.
I am using a dynamic variable in my code:
dynamic json = JObject.Parse(client.GetString().Result);
I'd been tinkering with other online guides the past few hours. However, can't get the result right.
Please help.
One solution would be to deserialize your JSON string into C# objects and then use Linq to get a specific object.
C# class definitions:
public class Content
{
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("value")]
public List<Value> Values { get; set; }
public Content()
{
Values = new List<Value>();
}
}
public class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
Deserializing and getting the object:
string json = #"{
""count"": 3,
""value"": [
{
""id"": ""AAAAAAAAAAAAA"",
""description"": ""test1"",
""name"": ""name1""
},
{
""id"": ""BBBBBBBBBB"",
""description"": ""test2"",
""name"": ""name2""
},
{
""id"": ""CCCCCCCCCCCC"",
""description"": ""test3"",
""name"": ""name3""
}
]
}";
Content content = JsonConvert.DeserializeObject<Content>(json);
Value value = content.Values.FirstOrDefault(x => x.Name.Equals("name1", StringComparison.InvariantCultureIgnoreCase));
First, you can create a class to represent a client:
public class Client
{
public string Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
With this class, you can use JObject.Parse (as you're already doing) to parse the JSON into something that can be queried, use SelectToken to pull out the value array and then use ToObject to convert that to a list of Clients. Here's what that looks like:
var jsonObject = JObject.Parse(json_source);
var jsonObjectValue = jsonObject.SelectToken("value");
var clients = jsonObjectValue.ToObject<List<Client>>();
Once you've got your clients variable, you can use a simple LINQ statement to find the one that is name1:
var clientWithName1 = clients.SingleOrDefault(x => x.Name == "name1");
In this case, clientWithName will be null if no such client was found.
Here's a dotnetfiddle that demonstrates a complete solution.
Create an object Client that has properties id, description and name. Deserialize the json into a list of these objects.
List<Client> clients = JsonConvert.Deserialize<List<Client>>(json_source);
string desc = clients[0].description;
Apparently with fiddling with my code I found an answer for myself.
Thanks for to the ones trying to help me for giving me ideas.
var requestWorkProcess = await client.GetStringAsync("my url");
var workProcessId = JObject.Parse(requestWorkProcess)["value"].Children<JObject>().FirstOrDefault(o => o["name"].ToString() == workProcess).GetValue("id");

Accessing a single value from a json file in c#

My json file looks something like this
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
so, i need to access the value of the buildno (2019) and assaign it to a variable in my program.
This is my class
public class lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
I tried this method using Newtonsoft.json
using (StreamReader r = new StreamReader(#"ba.json"))
{
string json2 = r.ReadToEnd();
lab item = JsonConvert.DeserializeObject<lab>(json2);
Console.WriteLine(item.buildno);
}
But I'm not getting any output!!! only blank screen.
You can make use of the following function to get a single value from json.
JObject.Parse()
Just pass the json returned by any of API's (if you are using) as a parameter to Parse function and get the value as follows:
// parsing the json returned by OneSignal Push API
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;
I was using OneSingal API to send push notifications and on hitting their API it returned a json object. And here 'recipients' was basically a key returned in the json.
Hope this helps someone.
jsong structure , given by you
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}
}
its not valid json structure , it should be like this
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
and then you C# class structure for that is
public class Lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
public class RootObject
{
public List<Lab> lab { get; set; }
}
if you do that then below code will work or code you are trying will work.
make use of Deserialize/serialize to convert you json in .net object type :make use of Newtonsoft library : Serializing and Deserializing JSON
Example :
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine( account.Email);
First of all you create a json object by
var lab = JSON.stringify({
"name": "blah",
"branch": "root",
"buildno": "2019"
});
then you can get this json object like this
dynamic model = JsonConvert.DeserializeObject(lab);
then you get value like as
lab l = new lab();
l.buildno = model.buildno;
Hopefully this help for you.

In C#, how do I model a JSON object with multiple nested arrays?

I am getting this JSON response from a system I am connecting to and trying to figure out the best way to deserialize it into a C# object. I am currently using RestSharp which seems pretty straight forward to use but the format of the JSON is baffling me a bit. Here is the format that its coming in as:
[
{"name": "Tickets:",
"schema": [
{"dataType": "string", "colName": "First", "idx": 0},
{"dataType": "string", "colName": "Second", "idx": 1},
{"dataType": "string", "colName": "Name", "idx": 2}
],
"data": [
["bill", "test", "joe"],
["bill2", "test2", "joe2"],
["bill3", "test3", "joe3"]
]
}
]
Here is my current code:
var url = "http://myUrl:10111";
var client = new RestClient { BaseUrl = url };
var request = new RestRequest { Method = Method.GET, Resource = "/search?fmt=Json", RequestFormat = DataFormat.Json };
request.AddHeader("accept", "application/json");
var response = client.Execute(request);
var wptResponse = new JsonDeserializer().Deserialize<TicketResults>(response);
return wptResponse;
but as stated above I am trying to figure out the correct way to model the TicketResults object to support deserializing this message above.
Ideally I would like something like this:
public class TicketResults
{
public List<Ticket> Tickets {get;set;}
}
public class Ticket
{
public string First {get;set;}
public string Second {get;set;}
public string Name {get;set;}
}
and in this example above would get three entries in the Tickets collection.
Also, is the above JSON format normal as i have never seen this broken out into separate schema and data section (I can see where it might save some space but in this case the messages are not that big)
In Visual Studio 2012 and up and you can go to Edit > Paste Special > Paste JSON as classes. It produces the following code given your example pasted from clipboard.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public Schema[] schema { get; set; }
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);
I agree the json format is quite ... goofy. Here's how to model your dto:
public class JsonDto
{
public string name { get; set; }
public Schema[] schema {get; set;}
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
I was able to get your string (unaltered) to deserialize with JSON.Net like this:
var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);
Let me know if you're still having trouble.
Do you have any control over the structure of the JSON being returned? It's kind of wacky. For some reason the field names and the data is separated out. If the format was a little more sensible like:
[
{
"First": "bill",
"Second": "test",
"Name": "joe"
},
{
"First": "bill2",
"Second": "test2",
"Name": "joe2"
},
]
Then you would have a shot at serializing it to your Ticket class. However, without reworking the JSON structure, which I don't recommend you do, the C# class that you are serializing to will have to match the JSON structure.
I suppose you could come up with an intermediary class to hold the JSON data as it comes to you. Then you could loop over those objets and create instances of the Ticket class out of them. At least that way you end up with a data structure you can work with.

How to convert Json array to list of objects in c#

I have Json string like below
{
"JsonValues":{
"id": "MyID",
"values": {
"value1":{
"id": "100",
"diaplayName": "MyValue1"
},
"value2":{
"id": "200",
"diaplayName": "MyValue2"
}
}
}
}
I want to convert Json string to below classes
class ValueSet
{
[JsonProperty("id")]
public string id
{
get;
set;
}
[JsonProperty("values")]
public List<Value> values
{
get;
set;
}
}
class Value
{
public string id
{
get;
set;
}
public string DiaplayName
{
get;
set;
}
}
My deserialization code is
JavaScriptSerializer js = new JavaScriptSerializer();
StreamReader sr = new StreamReader(#"ValueSetJsonString.txt");
string jsonString = sr.ReadToEnd();
var items = JsonConvert.DeserializeObject<ValueSet>(jsonString);
But I am getting null values after serialization, How i can solve this?
As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.
To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:
I added a Wrapper class corresponding to the outer object in your JSON.
I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
I added some additional [JsonProperty] attributes to match the property names in your JSON objects.
Class definitions:
class Wrapper
{
[JsonProperty("JsonValues")]
public ValueSet ValueSet { get; set; }
}
class ValueSet
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("values")]
public Dictionary<string, Value> Values { get; set; }
}
class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("diaplayName")]
public string DisplayName { get; set; }
}
You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Here is a working program to demonstrate:
class Program
{
static void Main(string[] args)
{
string jsonString = #"
{
""JsonValues"": {
""id"": ""MyID"",
""values"": {
""value1"": {
""id"": ""100"",
""diaplayName"": ""MyValue1""
},
""value2"": {
""id"": ""200"",
""diaplayName"": ""MyValue2""
}
}
}
}";
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Console.WriteLine("id: " + valueSet.Id);
foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
{
Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
}
}
}
And here is the output:
id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
http://json2csharp.com/
I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.
Then I called :
JsonConvert.DeserializeObject<RootObject>(jsonString);
and everything worked as expected.
Did you check this line works perfectly & your string have value in it ?
string jsonString = sr.ReadToEnd();
if yes, try this code for last line:
ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);
or if you have an array of json you can use list like this :
List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);
good luck
Your data structure and your JSON do not match.
Your JSON is this:
{
"JsonValues":{
"id": "MyID",
...
}
}
But the data structure you try to serialize it to is this:
class ValueSet
{
[JsonProperty("id")]
public string id
{
get;
set;
}
...
}
You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.
Also inside your class your JSON is this:
"values": { ... }
Your data structure is this:
[JsonProperty("values")]
public List<Value> values
{
get;
set;
}
Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.
Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.
If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1"
}, {
"id": "200",
"diaplayName": "MyValue2"
}
]
}
Json Convert To C# Class = https://json2csharp.com/json-to-csharp
after the schema comes out
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string myJSON = client.DownloadString("http://xxx/xx/xx.json");
var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);
The biggest one of our mistakes is that we can't match the class structure with json.
This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp
that's it.
you have an unmatched jSon string, if you want to convert into a list, try this
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1",
},
{
"id": "200",
"diaplayName": "MyValue2",
}
]
}
This is possible too:
using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);
This takes the JsonElement and deserializes it to List of objects.
List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());
Example:
[HttpPost]
[Route("CreateDraft")]
public async Task<IActionResult> CreateDraft([FromBody] JsonElement jsonDrafts)
{
List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());
for (int i = 0; i < draftInvoices.Count; i++)
{
........
}
You may use Json.Net framework to do this.
Just like this :
Account account = JsonConvert.DeserializeObject<Account>(json);
the home page : http://json.codeplex.com/
the document about this : http://james.newtonking.com/json/help/index.html#

JSON Can't be Deserialized to Object, Needs Array?

I am trying to take the incoming JSON items and bind them to listbox items but I am told by visual studio that I need to do an Array and not Object? I've never had to do this... Anyone know how?
My RootObject:
public class RootObject
{
public string url { get; set; }
public string display { get; set; }
public List<string> genetics { get; set; }
public List<string> price { get; set; }
public List<string> brandMaker { get; set; }
public string form { get; set; }
public string dosornos { get; set; }
public string qty { get; set; }
public string mfg { get; set; }
public string mobURI { get; set; }
}
Note: Genetics, Price, BrandMaker don't actually return anything but a value, like below:
"genetics": [
"typeophere"
],
"price": [
"$1400"
],
JSON FILE/REQUEST BASIC RESULT:
[
{
"url": "N/A",
"display": "",
"genetics": [
"microogiz"
],
"price": [
"96.016"
],
"brandMaker": [
"Oshi Kunti Multikashi, Osaka, JP"
],
"form": "tangent",
"dosornos": "n/a",
"qty": "88G",
"mfg": "SelfMade Industries, USA Dist.",
"mobURI": "n/a"
}
]
My original code:
// Get JSON via WEB
string ProviderURI = goURI;
webClient webClient = new WebClient();
webClient.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(ProviderURI));
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
return;
}
var deserializedJSON = JsonConvert.DeserializeObject<RootObject>(e.Result);
lstBoxResults.ItemsSource = deserializedJSON; // or deserializedJSON.url.ToString();
}
Ok, you mention that genetics and price are arrays, but the returned JSON only contains one item. The rest of your RootObject are simple string properties.
Since you did not post a raw JSON example. Let me present a trimmed down version, to keep things simple and short.
{
"url": "http://www.stackoverflow.com",
"display": "This is a test",
"genetics": [
"typeophere"
],
"price": [
"$1400"
],
"form": "a form"
}
Now we can trim down the RootObject class type. I used Pascal casing for my properties and attributed them with JSON.NET attributes to assist with the deserialing / serializing.
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class RootObject
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "display")]
public string Display { get; set; }
[JsonProperty(PropertyName = "genetics")]
public List<string> Genetics { get; set; }
[JsonProperty(PropertyName = "price")]
public List<string> Price { get; set; }
[JsonProperty(PropertyName = "form")]
public string Form { get; set; }
}
Since I don't know the web service you are calling I just stored this JSON in a text file. Marked it as an embedded resource and read it from there.
string json;
var resource = Application.GetResourceStream(new Uri("json.txt", UriKind.Relative));
using (var reader = new StreamReader(resource.Stream))
{
json = reader.ReadToEnd();
}
Just replace this part with your WebClient call to obtain your JSON data.
Now we can deserialize the JSON into a RootObject instance.
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Works as advertised. Now you need to bind it to a ListBox control. If you hover over the ItemSource property of your ListBox instance you'll see that the tooltip mentions that you can bind it to a collection. Well a single rootObject isn't a collection. You can't bind it directly.
lstBoxResults.ItemsSource = rootObject;
This will NOT work. You cannot convert a RootObject instance to a System.Collections.IEnumerable. Which is what ItemsSource is expecting.
Easy fix. Let's create a collection.
lstBoxResults.ItemsSource = new List<RootObject> { rootObject };
This is assuming that your JSON data only returns one rootObject. Only one item will appear in your ListBox.
Now let's suppose your JSON data returns an array of RootObjects. For example an array called "items" which contains a collection of RootItems.
{
"items": [
{
"url": "http://www.stackoverflow.com",
"display": "This is a test",
"genetics": [ "typeophere" ],
"price": [ "$1400" ],
"form": "a form"
},
{
"url": "https://github.com/geersch",
"display": "This is another test",
"genetics": [ "typeophere" ],
"price": [ "$2000" ],
"form": "another form"
}]
}
Deserialing this is equally easy. Using JSON.NET obtain the collection of RootObjects.
var data = JObject.Parse(json)["items"];
Now deserialize into a collection (IEnumerable).
var rootObjects = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(data.ToString());
Since you now already have a collection of RootObject there is no need to create one yourself. You can directly bind it to the ListBox.
lstBoxResults.ItemsSource = rootObjects;
Seems like the JSON data you receive is invalid. Just before parsing it make sure you modify it so that you have a valid JSON object.
For example:
json = json.Substring(json.IndexOf("[") + 1);
json = json.Substring(0, json.LastIndexOf("]"));
var rootObjects = JsonConvert.DeserializeObject<RootObject>(json);
Try this
RootObject rootObject;
if (json.startsWith("["))
{
rootObject = JsonConvert.DeserializeObject<List<RootObject>>(json)[0];
}
else
{
rootObject = JsonConvert.DeserializeObject<RootObject>(json);
}

Categories