json.net

JSON Deserialization - String Is Automatically Converted To Int

给你一囗甜甜゛ 提交于 2020-01-11 05:36:08
问题 When I deseiralize the JSON to the C# object below, either using Newtonsoft explicitly or via the model binding mechanism of ASP.NET Web Api, the string id value is automatically converted to int. I would expect it to throw an exception or raise an error as there is a type mismatch. Is this how JSON is supposed to work in the specs? If not, how can I prevent such an automatic conversion? JSON: {"id":"4", "name":"a"} C# model: int id; string name 回答1: This is a feature of Json.NET: when

How to combine/merge two JArrays in JSON.NET

♀尐吖头ヾ 提交于 2020-01-10 22:28:04
问题 I can't figure out how to concatenate two JArrays that I got be using JArray.Parse? The order of the arrays must be preserved i.e. the first array should be first and element in seconds should come afterwards. 回答1: You can add elements to one JArray by calling JArray.Add(element) where element comes from the second JArray. You'll need to loop over the second JArray to add all of these elements, but this will accomplish what you want: for(int i=0; i<jarrayTwo.Count; i++) { jarrayOne.Add

Possible to look for Key that does not exist in Json.net

走远了吗. 提交于 2020-01-10 17:20:55
问题 I got a couple different formats that come in but I can't figure out how to handle them all because when I try to find by key json.net crashes. I was hoping it would just return null. foreach (var item in jsonObj) { var msg = item.Value["Msg"]; if (msg != null) { txtErrors.Text += msg + Environment.NewLine; } } // format one {[UserNotFound, { "SeverityType": 3, "ValidationType": 2, "Msg": "Email Not Found" }]} my code works. // format 2 (came because I did not catch an exception on serverside

Serialize/Deserialize dynamic property name using JSON.NET

♀尐吖头ヾ 提交于 2020-01-10 05:57:25
问题 I have the following class: public class MyRequest { public string Type {get;set;} public string Source {get;set;} } I would like to serialize/deserialize the value for Source from the JSON field named the value of Type , for example: { "type": "bank", "bank": "Some value" } or { "type": "card", "card": "Some value" } Where both bind to the Source property. 回答1: You could create a custom JsonConverter to handle the dynamic property name: public class MyRequestConverter : JsonConverter {

Json.Net and validation of Enums in Web API

旧时模样 提交于 2020-01-10 05:40:09
问题 I'm writing a web api in .Net Core 2.2. I have an enumeration as follows: using System.Runtime.Serialization; namespace MyNamespace { public enum MyEnum { [EnumMember(Value = "Some Value")] SomeValue } } If I pass in random data as MyEnum in a request using the enum I rightly get an error, but if I pass "Some Value" or "SomeValue" it passes. How do I make "SomeValue" invalid? "SomeValue" isn't in my swagger and isn't a value I want to accept. So basically, model validation passes for

How to parse malformed JSONP with hex-encoded characters using JSON.NET?

和自甴很熟 提交于 2020-01-10 05:23:28
问题 I make a call to google's dictionary api like this: var json = new WebClient().DownloadString(string.Format(@"http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={0}&sl=en&tl=en", "bar")); However I get a response that this code fails to parse correctly: json = json.Replace("dict_api.callbacks.id100(", "").Replace(",200,null)", ""); JObject o = JObject.Parse(json); The parse dies at encountering this: "entries":[{"type":"example","terms":[{"type":"text","text":"\x3cem

JSON.net has @ in the attribute names?

天涯浪子 提交于 2020-01-10 05:08:37
问题 I am using JSON.NET and I want to convert from XML to JSON. I am using JsonConvert.SerializeXNode(node) and I noticed that my json object has properties with @ in front of their names: So for example: If I have: <channel id="999" name="XXX" sid="8294" type="Digital TV" /> the JSON object is: { "@id": "999", @name="XXX" etc Why am I getting "@" inserted in the JSON and is there a way I can avoid the "@" character being inserted? 回答1: I think thats just the way json.net works regarding the @

Turn C# object to json string, how to handle double quotation

一笑奈何 提交于 2020-01-10 03:56:54
问题 I'm using Newtonsoft.Json to parse object to json string. It returns somethink like this: {\"code\":-1,\"idName\":\"empty\",\"idValue\":0,\"message\":\"Failed,can not read object from body\"} it is not a valid json string i think, anyone can work me out? What I want is something like this: {"code":-1,"idName":"empty\",\"idValue\":0,\"message\":\"Failed,can not read object from body\"} public static class CommonUtility { // format response string public static string FormatResponseString(int

Deserializing nested JSON structure to a flattened class with Json.NET using annotations

拈花ヽ惹草 提交于 2020-01-10 02:20:07
问题 Is it possible to use JsonProperty annotation to map a nested Json property to a non-nested .NET member? Say you've got some Json like this: { "id":9999, "created_date":"Thu, 23 Jun 2011 12:56:24 +0000", "pos":{ "type":"someType", "coordinates":[ 59.323, 18.0654 ] } } and want to deserialize it into a flattened class MyClass using JsonConvert.DeserializeObject<MyClass>(jsonstr); Can annotations be used to map the Json coordinates list to Lat and Lng in the class below: public class MyClass {

How to serialize only inherited properties of a class using a JsonConverter

这一生的挚爱 提交于 2020-01-09 08:21:12
问题 I'm trying to serialize only the inherited properties of a class using json.net. I'm aware of the [JsonIgnore] attribute, but I only want to do ignore them on certain occasion, so I used a custom JsonConverter instead. Here's my class: public class EverythingButBaseJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // Find properties of inherited class var classType = value.GetType(); var classProps = classType