how to create json feed [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
any one explain me how to develop following type of json.
Json feed contains parent and child nodes with database comtent.
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
]
}

Go to this site and paste your json. It will create the following classes for you
public class Phone
{
public string mobile { get; set; }
public string home { get; set; }
public string office { get; set; }
}
public class Contact
{
public string id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string address { get; set; }
public string gender { get; set; }
public Phone phone { get; set; }
}
public class RootObject
{
public List<Contact> contacts { get; set; }
}
Create the RootObject, fill the properties and then serialize it.
That is all.
var root = new RootObject();
//fill the properties
string json = JsonConvert.SerializeObject(root);

Related

Newtonsoft JSON Deserialization not working as expected [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 13 hours ago.
Improve this question
Given this JSON
{
"docType": "payment-remittance-v1.4",
"fields": {
"Customer Name": {
"type": "string",
"valueString": "xxx",
"spans": [
{
"offset": 284,
"length": 43
}
]
},
"Payment Reference": {
"type": "string",
"valueString": "3875014846",
"content": "3875014846",
"confidence": 0.92,
"spans": [
{
"offset": 167,
"length": 10
}
]
},
"Remittance Date": {
"type": "date",
"content": "16.02.2023",
"confidence": 0.97,
"spans": [
{
"offset": 180,
"length": 10
}
]
},
},
"confidence": 0.125,
"spans": [
{
"offset": 0,
"length": 1048
}
]
}
And these classes
public class PredictionFields
{
[JsonProperty("Customer Name", Required = Required.Always)]
public BaseField CustomerName { get; set; }
[JsonProperty("Payment Reference", Required = Required.Always)]
public BaseField PaymentReference { get; set; }
}
public class BaseField
{
[JsonProperty("confidence")]
public double Confidence { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("valueNumber")]
public double ValueNumber { get; set; }
[JsonProperty("valueString")]
public string ValueString { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
public class Document
{
[JsonProperty("docType")]
public string DocType { get; set; }
[JsonProperty("fields")]
public PredictionFields Fields { get; set; }
[JsonProperty("confidence")]
public double Confidence { get; set; }
}
I get an error Unhandled exception. Newtonsoft.Json.JsonSerializationException: Required property 'Customer Name' not found in JSON. Path 'fields', line 82, position 3.
I'm perplexed as to this because the property is defintely listed in the JSON.
I have created a .NET Fiddle - be glad of any help, have been puzzling this for hours!
Adding the Property Name to PredictionFields should solve the problem:
public class PredictionFields
{
[JsonProperty("Customer Name", Required = Required.Always, PropertyName = "Customer Name")]
public BaseField CustomerName { get; set; }
[JsonProperty("Payment Reference", Required = Required.Always, PropertyName = "Payment Reference")]
public BaseField PaymentReference { get; set; }
}

ASP.NET Core Web API Posts All Enums as 0th Option [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have started building a webapi. I have a model class like so:
public class ParentItem
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Profession { get; set; }
public string PhoneNumber { get; set; }
public CaretakerType Caretaker { get; set; }
public string Email { get; set; }
}
public enum CaretakerType
{
Father,
Mother,
LegalGuardian,
EmergencyContact
}
The post method at the moment is just the default
[HttpPost]
public async Task<ActionResult<ParentItem>> PostParentItem(ParentItem parentItem)
{
_context.ParentItems.Add(parentItem);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetParentItem), new { id = parentItem.Id }, parentItem);
}
However, whenever I test the post method with postman, like so:
{
"firstName": "Person",
"lastName" : "Name",
"address" : "an address",
"profession": "a profession",
"phoneNumber": "a number",
"caretakerType": "Mother",
"email": "an email"
}
With Raw radio button and as type JSON, it always returns
{
"id": 1,
"firstName": "Person",
"lastName": "Name",
"address": "an address",
"profession": "a profession",
"phoneNumber": "a number",
"caretaker": "Father",
"email": "an email"
}
It doesn't matter if I say Mother, LegalGuardian, or EmergencyContact it always comes back as "Father." Why is this? Target Framework is net5.0. I am using EntityFrameworkCore.SqlServer and EntityFrameworkCore.InMemory at the moment.
Your JSON has a different name to your DTO class's property name.
public class ParentItem
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Profession { get; set; }
public string PhoneNumber { get; set; }
public CaretakerType Caretaker { get; set; } // <---- "Caretaker"
public string Email { get; set; }
}
{
"firstName": "Person",
"lastName" : "Name",
"address" : "an address",
"profession": "a profession",
"phoneNumber": "a number",
"caretakerType": "Mother", // <-- "caretakerType"
"email": "an email"
}
Change your JSON to this:
{
"firstName": "Person",
"lastName" : "Name",
"address" : "an address",
"profession": "a profession",
"phoneNumber": "a number",
"caretaker": "Mother", // <-- "caretaker"
"email": "an email"
}

Converting an object into json in specific format [duplicate]

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 8 years ago.
My required json format is
{
"nodes": {
"1": {
"attriba": "a1",
"attribb": "b1",
"label": "1",
"attribc": false
},
"2": {
"attriba": "a2",
"label": "2",
"attribc": false
},
"3": {
"attriba": "a3",
"label": "3",
"attribc": false
},
"4": {
"attriba": "none",
"label": "4",
"attribc": false
},
"5": {
"attriba": "none",
"label": "5",
"attribc": false
}
}
}
Now normally I would create classes and fill them with data and call "Newtonsoft.Json.JsonConvert.SerializeObject" to get the desired json string.
But in this case the format is such that I'm unable to figure out the class structure..
The top class I think would be like the following..
public class Response
{
[JsonProperty("nodes")]
public List<Node> Nodes { get; set; }
}
The bottom class ..
public class Nodedata
{
[JsonProperty("attriba")]
public string Attriba { get; set; }
[JsonProperty("attribb")]
public string Attribb { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("attribc")]
public bool Attribc { get; set; }
}
But, how do i manage the node class( values "1" to "5") which has no key value..
Any help will be sincerely appreciated..
Thanks
public class Response
{
public Dictionary<string, Node> nodes {get;set;}
}
public class Node
{
public string attriba { get; set; }
public string attribb { get; set; }
public string label { get; set; }
public bool attribc { get; set; }
}

Deserializing JSON that has an int as a key in C#

I am trying to deserialize this JSON
{
"39": {
"category": "Miscellaneous",
"country_whitelist": [],
"name": "domain.com",
"url_blacklist": [],
"country_blacklist": [],
"url_whitelist": [
"domain.com"
],
"deals": {
"425215": {
"status": "Ok",
"type": "",
"code": "CODE",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle",
"url": "http://domain.com/foo",
"text": "Text Text Text",
"long_title": "Longer Text"
},
"425216": {
"status": "Ok",
"type": "",
"code": "CODE2",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle2",
"url": "http://domain.com/bar",
"text": "Text Text Text",
"long_title": "Longer Text"
}
},
"88x31": "http://someimage/88x31.png",
"subcategory": "Other"
},
"40": {
"category": "Miscellaneous",
"country_whitelist": [],
"name": "domain.com",
"url_blacklist": [],
"country_blacklist": [],
"url_whitelist": [
"domain.com"
],
"products": {
"425215": {
"status": "Ok",
"type": "",
"code": "CODE",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle",
"url": "http://domain.com/foo",
"text": "Text Text Text",
"long_title": "Longer Text"
},
"425216": {
"status": "Ok",
"type": "",
"code": "CODE2",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle2",
"url": "http://domain.com/bar",
"text": "Text Text Text",
"long_title": "Longer Text"
}
},
"88x31": "http://someimage/88x31.png",
"subcategory": "Other"
}
}
I tried using Json.NET and I tried using ServiceStack's deserializer but I can't seem to get any type of representation for this JSON.
The main thing that is blocking me I believe is that the keys are Int but I don't have control on the JSON I receive.
This is the C# classes I have built
public class product
{
public string status { get; set; }
public string type { get; set; }
public string code { get; set; }
public string end_date { get; set; }
public string title { get; set; }
public string url { get; set; }
public string text { get; set; }
public string long_title { get; set; }
}
public class Merchant
{
public string category { get; set; }
public List<string> country_whitelist { get; set; }
public string name { get; set; }
public List<string> url_blacklist { get; set; }
public List<string> country_blacklist { get; set; }
public List<string> url_whitelist { get; set; }
public List<product> products { get; set; }
public string subcategory { get; set; }
}
public class Data
{
public Dictionary<int, Merchant> MainMerchants { get; set; }
}
I prefer using ServiceStack but any other deserializer that works will be great
var data = client.Get(json);
Getting your data types mapped correctly:
It is possible to deserialize your JSON. As you correctly identified you can deserialize to a Dictionary<int, Merchant>.
But you will need to change your definition of products in the Merchant class to be a Dictionary<int, Product>. It needs to be a dictionary here to handle your numeric key. List<Product> won't work.
Also to handle the 88x31 property you can use a DataMember(Name = '88x31') mapping to map it to something c# likes, like image88x31. Unfortunately this does mean your DTO properties become opt-in so you will then need to decorate all members. Add using System.Runtime.Serialization;
Once you make those changes such that:
// Note I capitalized Product
public class Product
{
public string status { get; set; }
public string type { get; set; }
public string code { get; set; }
public string end_date { get; set; }
public string title { get; set; }
public string url { get; set; }
public string text { get; set; }
public string long_title { get; set; }
}
/*
* Use DataMember to map the keys starting with numbers to an alternative c# compatible name.
* Unfortunately this requires properties to opt in to the data contract.
*/
[DataContract]
public class Merchant
{
[DataMember]
public string category { get; set; }
[DataMember]
public List<string> country_whitelist { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public List<string> url_blacklist { get; set; }
[DataMember]
public List<string> country_blacklist { get; set; }
[DataMember]
public List<string> url_whitelist { get; set; }
[DataMember]
public Dictionary<int, Product> products { get; set; }
[DataMember]
public string sub_category { get; set; }
// This maps the 88x31 key to a c# appropriate name
[DataMember(Name = "88x31")]
public string image88x31 { get; set; }
}
Then you will be able to deserialize into Dictionary<int, Merchant> without any issues.
JsonSerializer.DeserializeFromString<Dictionary<int, Merchant>>("YOUR JSON STRING");
Using in a ServiceStack Service:
If you want to be able to send this request directly to a ServiceStack service, then you can use a RequestBinder to deserialize into this complex type. Given this service:
Request DTO:
[Route("/Merchants", "POST")]
public class MerchantsRequest
{
public Dictionary<int, Merchant> MainMerchants { get; set; }
}
Simple Action Method:
public class MerchantsService : Service
{
public void Post(MerchantsRequest request)
{
var merchant39 = request.MainMerchants.First(p=>p.Key == 39).Value;
Console.WriteLine("Name: {0}\nImage: {1}\nProduct Count: {2}", merchant39.name, merchant39.image88x31, merchant39.products.Count);
var merchant40 = request.MainMerchants.First(p=>p.Key == 40).Value;
Console.WriteLine("Name: {0}\nImage: {1}\nProduct Count: {2}", merchant40.name, merchant40.image88x31, merchant40.products.Count);
}
}
AppHost Configuration:
In your AppHost Configure method you would need to add a binder to the request type. i.e. typeof(MerchantsRequest) like so:
public override void Configure(Funq.Container container)
{
Func<IRequest, object> merchantsRequestBinder = delegate(IRequest request) {
var json = WebUtility.HtmlDecode( request.GetRawBody() );
return new MerchantsRequest { MainMerchants = JsonSerializer.DeserializeFromString<Dictionary<int, Merchant>>(json) };
};
RequestBinders.Add(typeof(MerchantsRequest), merchantsRequestBinder);
...
}
This binder method will convert the json you are sending into a MerchantsRequest. Then you can use it like a regular ServiceStack request.
Full Source Code Here
A fully working example of console application, demonstrating the conversion of the complex JSON to a service request.
Note: I notice in your JSON that you have property deals on one object, and products on another, I assumed this was a typo, as you don't have a corresponding property on in the class for deals.
In your json string, for the products node, should it be this? as the type where it converted from is a List instead of dictionary?
I can get it work change it to following json string
"products": [{
"status": "Ok",
"type": "",
"code": "CODE",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle",
"url": "http://domain.com/foo",
"text": "Text Text Text",
"long_title": "Longer Text"
},
{
"status": "Ok",
"type": "",
"code": "CODE2",
"end_date": "2014-03-01 04:00:00",
"title": "RandomTitle2",
"url": "http://domain.com/bar",
"text": "Text Text Text",
"long_title": "Longer Text"
}],

How to create a listbox view inside the single item view in windows phone 8? With Async JSON from a url

I want to create a List Box for a Json Form a url..
I am getting Json data form a URL. I already parsed JSON data..
My JSON data Contains a Product base process in but I parsed the JSON data by this way.
Like that I followed many tutorials.. but My JSON data May products information that's not constant for example I already parsed data regarding web sites.. now I want to parse the data for movies or products But for every time I need to change the data I want it like automatically changes I already done this application on java for parsing JSON I used Hashmap.. but now in Windows I got get,set but its Working for only one product..
And One more thing.. In Android I did a List view which will like this..
So I want to display images including the data.. I already done this on Android but I want to build this in Windows..
In that I want a List Box .. like image so when I click on any item form list box .. it should display and again it should have a list or table..
In Android I did it with Listview to singleitemview in that single item view I added a Table layout..
I am stuck at these cases..
In android for one Class file i can use many xml files.. but here Xaml is main and it has only one class file..
When I am displaying data in android it is an async task.. so that right now its about flags next its about some other.. I mean if its
about product for first time its for mobiles then PC..
But its not possible in windows if there tell me any way
For parsing JSON in Android I used JSON array and JSON object with Hashmap..
But in windows I found only GET,set..
Is there any way to Build like this? I am new to Windows Phone..
This Is my Json data.
{
"returnCode": "success",
"SPData": {
"result": [
{
"sdetails": [
{
"loffers": [
{
"id": "wKugoi00AOWi",
"price": "129.99",
"seller": "Google"
}
],
"O_count": 1,
"name": "google.com",
"r_count": 1,
"sku": "68190",
"url": "http://www.google.com"
},
{
"loffers": [
{
"id": "wAOWi",
"price": "129.99",
"seller": "Yahoo"
},
{
"id": "wKuAOWi",
"price": "130.99",
"seller": "Yahoo"
},
{
"id": "wKuWi",
"price": "123.99",
"seller": "Yahoo"
}
],
"offers_count": 3,
"name": "yahoo.com",
"r_count": 1,
"sku": "68190",
"url": "http://www.yahoo.com"
},
{
"loffers": [
{
"id": "7e8Wk",
"price": "99.99",
"seller": "amazon.com"
},
{
"id": "4XUaGAi",
"price": "129.99",
"seller": "amazon.com"
}
],
"offers_count": 2,
"name": "amazon.com",
"recentoffers_count": 1,
"sku": "7829033",
"url": "http://www.amazon.com"
}
],
"model": "AAA",
"weight": "1258.64",
"price_currency": "USD",
"gtins": [
"008411"
],
"mpn": "AAAAA",
"amam3_help": "To view additional merchants for this product, please upgrade your plan.",
"cat_id": "20780",
"height": "40.64",
"description": "Immersive action and endless unready to discover a... (visit site URLs for full description)",
"name": "xyz",
"features": {
"Wi-Fi Ready": "No",
"BD Live": "Yes",
"Coaxial Digital Audio Outputs": "1 [Connections that deliver audio signals to compatible A/V components in digital form. ]",
"Audio Outputs": "1 [Jacks that send audio signals to another A/V component. ]"
},
"length": "198.12",
"created_at": 1364157755,
"geo": [
"usa"
],
"width": "358.14",
"upc": "027242858411",
"ean": "0027242858411",
"category": "Blu-ray Players",
"price": "139.99",
"updated_at": 1390272838,
"manufacturer": "Sony",
"images_total": 1,
"images": [
"http://cpcstrategy.com/wp-content/uploads/2013/06/Google-logo-retargeting.jpg"
],
"brand": "Google",
"aam3_id": "4FyI",
"offers_total": 404
}
],
"total_results_count": 3,
"results_count": 3,
"code": "OK",
"offset": 0
}
}
So if I follow Get and set the Features always may not be same.. So over there I will get error..
In android I am parsing by this way..
JSONObject json_data = JSONfunctions.getJSONfromURL(url);
JSONObject json_query = json_data.getJSONObject("query");
JSONArray json_result = json_query.getJSONArray("result");
for (int i = 0; i < json_results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = json_result.getJSONObject(i);
.
.
JSONArray flag = c.getJSONArray("flag");
for(int s=0;s<flag.length();s++)
{
System.out.println("URL"+flag.getString(s));
map.put("flag", flag.getString(s));
}
.
.
JSONArray json_result_site =c.getJSONArray("site");
for (int j = 0; j < c.length(); j++) {
if (j < json_result_site.length()) {
JSONObject s= json_result_site.getJSONObject(j);
map.put("url", s.optString("url"));
JSONArray json_latest = s.getJSONArray("latest");
for (int k = 0; k < json_latest.length(); k++) {
JSONObject e = json_latest.getJSONObject(k);
map.put("id", e.optString("id"));
map.put("date", e.optString("date"));
}
}
}
}
arraylist.add(map);
}
}
Is there any way to load the data in C#..
just like above..
Windows phone give you the ability to do what you asked for easily by using DataBining ,all you have to do is binding your data source with XAML control and then format your XAML control template.
You are using List View in android but in windows Phone you can LongListSelector control
To know more about Data Binding and LongListSelector take a look to the following articles.
Windows Phone Data Binding
Data Binding to controls on Windows Phone
Windows Phone 8 XAML LongListSelector
Implementing the Model-View-ViewModel pattern in a Windows Phone app
SubList inside the main List. May be you are looking for a long list selector.
Taken from the links given below
LongListSelector which is actually an advanced ListBox that supports full data and UI virtualization, flat lists and grouped lists. It helps users to scroll through long lists of data. Basically a quick jump grid overlays the list when the user select one of the group headers after that when an item is selected from the grid the user is automatically redirected back to the long list at the selected point.
it also comes up with ways to manage headers and contents separately and efficiently.
Best Links to take a start with
One
Two
The c# class structure that gets generated from your JSON data
public class Loffer
{
public string id { get; set; }
public string price { get; set; }
public string seller { get; set; }
}
public class Sdetail
{
public List<Loffer> loffers { get; set; }
public int O_count { get; set; }
public string name { get; set; }
public int r_count { get; set; }
public string sku { get; set; }
public string url { get; set; }
public int? offers_count { get; set; }
public int? recentoffers_count { get; set; }
}
public class Features
{
public string __invalid_name__Wi-Fi Ready { get; set; }
public string __invalid_name__BD Live { get; set; }
public string __invalid_name__Coaxial Digital Audio Outputs { get; set; }
public string __invalid_name__Audio Outputs { get; set; }
}
public class Result
{
public List<Sdetail> sdetails { get; set; }
public string model { get; set; }
public string weight { get; set; }
public string price_currency { get; set; }
public List<string> gtins { get; set; }
public string mpn { get; set; }
public string amam3_help { get; set; }
public string cat_id { get; set; }
public string height { get; set; }
public string description { get; set; }
public string name { get; set; }
public Features features { get; set; }
public string length { get; set; }
public int created_at { get; set; }
public List<string> geo { get; set; }
public string width { get; set; }
public string upc { get; set; }
public string ean { get; set; }
public string category { get; set; }
public string price { get; set; }
public int updated_at { get; set; }
public string manufacturer { get; set; }
public int images_total { get; set; }
public List<string> images { get; set; }
public string brand { get; set; }
public string aam3_id { get; set; }
public int offers_total { get; set; }
}
public class SPData
{
public List<Result> result { get; set; }
public int total_results_count { get; set; }
public int results_count { get; set; }
public string code { get; set; }
public int offset { get; set; }
}
public class RootObject
{
public string returnCode { get; set; }
public SPData SPData { get; set; }
}
Now debugging and checking for the RootObject in the list you are getting could give you every nested item.

Categories