I am using post method in that method i want to pass entire Json in string like this way
{Data:" JsonArray"} in Jssonarray I want to pass this value
{ "version" : 2,
"query" : "Companies, CA",
"begin" : 1,
"end" : 3,
"totalResults" : 718,
"pageNumber" : 0,
"results" : [
{ "company" : "ABC Company Inc.", "city" : "Sacramento", "state" : "CA" } ,
{ "company" : "XYZ Company Inc.", "city" : "San Francisco", "state" : "CA" } ,
{ "company" : "KLM Company Inc.", "city" : "Los Angeles", "state" : "CA" }
]
}
When i pass this I am getting 500 internal Error
Please help me how to pass Entire Json in a single string.
One way is to navigate to http://json2csharp.com/, paste your Json and hit "GO".
The result will be this one (I fixed the capitalization):
public class Result {
public string Company { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class RootObject {
public int Version { get; set; }
public string Query { get; set; }
public int Begin { get; set; }
public int End { get; set; }
public int TotalResults { get; set; }
public int PageNumber { get; set; }
public Result[] Results { get; set; }
}
Paste this into your application.
Your POST-Method then could look like this:
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(RootObject root) {
// do something with your root objects or its child objects...
return new HttpResponseMessage(HttpStatusCode.Created);
}
And you're done with this method.
Another method is to use the new JsonValue and JsonArray introduced with Web API whereas you don't need RootObject and Result.
Just use your POST-Method:
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
JsonArray arr = (JsonArray) json["results"];
JsonValue result1 = arr[0];
var company = result1["company"]; // results in "ABC Company Inc."
return new HttpResponseMessage(HttpStatusCode.Created);
}
You should get a clue...
You can prettify the whole thing:
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
var arr = json["results"];
var result1 = arr[0];
var company = result1["company"]; // results in "ABC Company Inc."
return new HttpResponseMessage(HttpStatusCode.Created);
}
Related
I have this json and need to parse the nested details. using Newtonsoft.Json for Deserializing but cant really parse this complex json.
{
"name": "John",
"email": "john#gmail.com",
"data": [
{
"company_name": "instagram",
"company_email": "abc#email.com",
"org": {
"org_name": "john-insta",
"org_dob": "1/1/1990",
}
},
{
"company_name": "google",
"company_email": "abc1#email.com",
"org": {
"org_name": "john-google",
"org_dob": "1/1/1990",
}
},
]
The number of entries in "data" may actually be varying dynamically, how do I parse the entries for company_name, company_email, org_name,org_dob.
What is the problem you are having? This seems fairly simple JSON array. Setup your classes like this.
public class MyClass
{
public string name { get; set; }
public string email { get; set; }
public List<DataClass> data { get; set; }
}
public class DataClass
{
public string company_name { get; set; }
public string company_email { get; set; }
public Org org { get; set; }
//Any other and all possible properties...
}
public class Org
{
public string org_name { get; set; }
public string org_dob { get; set; }
}
Then it can be parsed using Newtonsoft or similar using.
var test = JsonConvert.DeserializeObject<MyClass>(json);
This method also has an overload where you can pass settings to ignore nulls.
var test = JsonConvert.DeserializeObject<MyClass>(json,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
I'm trying to get a JSON file into a SQL Server database with auto identity keys and the correct foreign key relation. Everything is working gloriously with the exception of a string array. The data looks more or less like this:
{
"id" : "123",
"name" : "Some Stuff",
"phrase" : "More Stuff",
"type" : "ABC",
"label" : "Some label",
"responseType" : "The Response Type",
"answers" : [ "9" ]
}
The "answers" part is causing me fits. It looks like it's almost exclusively a single value, but it could potentially have multiple values like
"answers" : [ "6", "7", "8" ]
Now I know that a List is not supported in EF for native types like string or int. I ultimately would rather have a separate table for the list of answer values anyway, which I'm calling DataAnswers.
public partial class Response
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ResponseId { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("phrase", NullValueHandling = NullValueHandling.Ignore)]
public string Phrase { get; set; }
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public string Type { get; set; }
[JsonProperty("label", NullValueHandling = NullValueHandling.Ignore)]
public string Label { get; set; }
[JsonProperty("responseType", NullValueHandling = NullValueHandling.Ignore)]
public string ResponseType { get; set; }
[JsonProperty("answers", NullValueHandling = NullValueHandling.Ignore)]
public virtual List<DataAnswer> DataAnswers { get; set; }
}
public partial class DataAnswer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DataAnswerId { get; set; }
public string AnswerText { get; set; }
}
Currently here's the error I'm getting.
Newtonsoft.Json.JsonSerializationException: 'Error converting value
"9" to type 'ForeseeDemo.Data.DataAnswer'. Path
'items[0].responses[0].answers[0]', line 60, position 23.'
Any great ideas of how to get a list of answer strings into a table with a foreign key to the Response ?
Thanks in advance!
You could create a data transfer object then handle the conversion b/t that and the entity object.
You could create a custom JSON converter to handle conversion of the property.
You could create an additional property that is used for serialization/deserialization but not by EF and handle conversions there:
[JsonIgnore]
public virtual List<DataAnswer> DataAnswers { get; set; }
[NotMapped]
[JsonProperty( "answers", NullValueHandling = NullValueHandling.Ignore )]
public List<string> DataAnswerStrings
{
get => DataAnswers?.Select( da => da.AnswerText )?.ToList();
set => DataAnswers = value
?.Select( s => new DataAnswer() { AnswerText = s } )
?.ToList()
?? new List<DataAnswer>();
}
I've been tasked will calling an API, that needs to take a JSON payload as its request.. An example format of the JSON is as follows:
{
"method":"methodname",
"in":[
{
"account":"acme",
"context":"abc123"
},
"content",
{
"mSearchText":"chocolate",
"mItemDataIDs":[
"Entry:ID",
"Entry:EntryRef",
"Entry:CategoryID"
]
}
]
}
I am using JSON.NET (Newstonsoft) to construct my JSON from .net objects.
The issue I am facing is correctly constructing the "in" section..
It appears to be an array of objects, but only the second item has a title ("content",{.....})..
The closest I can get is:
{
"method": "methodname",
"in":[
{
"account": "PANDO",
"context": "sdfsd22342"
},
{
"mSearchText":"chocolate",
"mItemDataIDs":[
"Entry:ID",
"Entry:EntryRef",
"Entry:CategoryID"
]
}
]
}
Which is identical apart from "content", is missing:
My code so far is:
public class Payload
{
public string method { get; set; }
[JsonProperty("in")]
public List<object> Items { get; set; }
}
public class AccountDetails
{
public string account { get; set; }
public string context { get; set; }
}
[JsonObject(Title = "content")]
public class Content
{
public string mSearchText { get; set; }
public string[] mItemDataIDs { get; set; }
}
Payload payload = new Payload();
payload.method = "methodname";
payload.Items = new List<object>();
payload.Items.Add(new AccountDetails
{
account = "acme",
context = "abc123"
});
Content conent = new Content
{
mSearchText = "chocolate",
mItemDataIDs = new string[] { "Entry:ID", "Entry:EntryRef", "Entry:CategoryID" }
};
payload.Items.Add(conent);
string jsonObject = JsonConvert.SerializeObject(payload, Formatting.Indented);
Any suggestions on what I can do?
First of all, I know that it's not valid JSON format, but it's my customer web service settings, I need to set QuoteName of Json.Net JsonTextWriter to be false, but I don't know how to do it properly. This is my try:
foreach (var c in a)
{
var jsonobjects = JsonConvert.SerializeObject(c, new JsonTextWriter
{
QuoteName = false
}
);
//Some code that using serialized json object
}
In order to clarify what I want. I need to have Json property name without quotes. Something like that: {Property: "Value"}.
Here is an example:
The class:
public class Address
{
public string Street { get; set; }
public uint Number { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
Serialization logic:
var address = new Address
{
Street = "Fulton Street",
Number = 100,
City = "New York",
ZipCode = "10038",
State = "NY",
Country = "USA"
};
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
{
writer.QuoteName = false;
serializer.Serialize(writer, address);
}
var json = stringWriter.ToString();
Console.WriteLine(json);
Output:
{
Street: "Fulton Street",
Number: 100,
City: "New York",
ZipCode: "10038",
State: "NY",
Country: "USA"
}
Example:
https://dotnetfiddle.net/zazT1T
My Json is of the following format.
{
"code" : o,
"message" : "success",
"book_list":
[
{"name": "C","price":180},
{"name": "C++","price":180},
{"name": "C#","price":180},
]
}
I am a brand new beginner to Windows phone app development!!
How shall i get list of books from the url and store it in a dictionary kind of thing??(i.e as a key value pair) for windows phone 7??
You can use this JSON framework for .NET:
using System.Runtime.Serialization;
[DataContract]
public class BookShop
{
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "book_list")]
public List<Book> Result { get; set; }
}
[DataContract]
public class Book
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "price")]
public int Price { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
string json = "{\"code\": 0,\"message\": \"success\",\"book_list\": [{\"name\": \"C\",\"price\": 180}, {\"name\": \"C++\",\"price\": 180 }, {\"name\": \"C#\",\"price\": 180}]}";
var myObjects = JsonConvert.DeserializeObject<BookShop>(json);
foreach (var item in myObjects.Result)
{
Debug.WriteLine("{0} has price {1}", item.Name, item.Price);
}
}
}