FAQ Database Discussion Community


How can I get a list from a json file in c#? [closed]

c#,json,windows-phone-8.1,json.net
I am trying to display a list pulled from the eztv.re API in a listbox. I have tried using: using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(("http://eztvapi.re/shows/1&query_term=" + SearchTextBox.Text))) { using (Stream stream = response.Content.ReadAsStreamAsync().Result) { using (StreamReader reader = new StreamReader(stream)) { string json...

Is there a Json library that works with both array of objects and array of abstract classes? [closed]

.net,json,json.net,servicestack-text
I need read/write Json from/to a POCO that is decorated with XmlSerialization attributes. This POCO has been generated from an XSD. It makes extensive use of polymorphism, inheritance, objects, arrays of objects and array of abstract classes. I've already tried JsonFx V2 that looked very promising but unfortunately this is...

JSON serialization using newtonsoft in C#

c#,json,serialization,json.net,jsonserializer
I have the following model structure. public class ReferenceData { public string Version { get; set; } public List<DataItem> Data { get; set; } } public class DataItem { public Dictionary<string, string> Item { get; set; } } In the dictionary i'm adding the key value pair and serializing with...

How get value from JSON string?

c#,json,json.net
I convert collection to JSON string. ReadOnlyCollection<Post> wall = api.Wall.Get(-group.Id.Value, out totalCount, count); string json = JsonConvert.SerializeObject(wall, Formatting.Indented); get string json like this [ { "Id": 144159, "Text": "Если", "Likes": { "Count": 9307, "UserLikes": false, "CanLike": true, "CanPublish": true }, "PostType": "post", "PostSource": { "Type": "api", "Data": null }, "Attachments":...

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

Converting Json.Net JValue to int

c#,json.net
I've tried: JValue myJValue = getJValue(someVar); int storedValue = JsonConvert.DeserializeObject(myJValue); But this only seems to be valid for JObjects. Is there a way to get the integer from a JValue? ...

How can I stop my ClickOnce install from requiring Newtonsoft.Json v4.5 in the GAC?

wpf,json.net,nuget,clickonce
We have a ClickOnce deployment of a WPF desktop application, and recently installed the Newtonsoft.Json version 6.0.8 nuget package. After making this change and publishing the ClickOnce deployment, users can't run the update, because of this error message: The first thing that strikes me as odd is the dependency on...

newtonsoft.json deserializing logic

c#,json.net
I'm trying to parse a json string with for example [1,2,3] to an array during deserializing. This is my json data: [ { "id": "1", "district": "1", "lon": "4.420650000000000000", "lat": "51.21782000000000000", "bikes": "19", "slots": "14", "zip": "2018", "address": "Koningin Astridplein", "addressNumber": null, "nearbyStations": "3,4,5,24", "status": "OPN", "name": "001- Centraal Station...

How to accept multiple names for a single property on newtonsoft JSON de-serialization?

c#,json,json.net
We have a standard json format that we defined (the typo is on purpose): { "Name" : "John", "Salari" : "150000" } which is de-serialized (using newtonsoft) to: class Person { public string Name; public string Salari; } Is there a way to change Salari to Salary and still be...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0
I have an upload control. But if the user didnt select an image and the press on the upload button, the user will get an message that he/she has to go back and try again, like this: if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { return Json(new...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

JSON.net CF 3.5, verify that JSON is complete

c#,json,json.net,compact-framework
I'm using Json.net in a 3.5 CF setting and have a problem verifying that a string is indeed complete JSON. I am using: var o = JObject.Parse(incomingString); which will return null if the JSON is incomplete - but not always. If the JSON is something "mostly formed", it will parse...

Serialize a Json property that is sometimes an array [duplicate]

c#,json.net
This question already has an answer here: How to handle both a single item and an array for the same property using JSON.net 3 answers Is there any way to serialize a Json object property that varies from decimal to decimal[] in a single operation? In my Json product...

Populating non-serializable object with Json.NET

c#,.net,json,json.net
In a test I want to populate an object (a view model) from a JSON string. For example, the target object has this property: public string Query { get; set; } So I want to be able to do this: var target = ...; JsonConvert.PopulateObject(target, "{ 'Query': 'test' }"); However,...

json.Net save to file

c#,json,json.net
I have a script for saving to file sorted, however I cant code it to save to entry: as below { "entry": [ { "Name": "John" }, { "Name": "Anna" }, { "Name": "Peter" } ] } Im using json.Net, code below needs to add to entry: name string json...

How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET

json,serialization,json.net,partial
I have a situation in which I have a very large C# object, however, I only need to return a handful of properties (which can be on nested objects), allow for client-side JavaScript to modify those properties and then send the resulting object back to the server in order to...

MSpec Json.NET deserialization test fails in ReSharper but passes in NCrunch

c#,json.net,resharper,mspec,ncrunch
I have the following two unit tests: one using MSTest and one using Machine Specifications. As far as I can see they should behave identically. However, while the first one passes in both the NCrunch and ReSharper test runners, the second one fails in ReSharper. using Machine.Specifications; using Microsoft.VisualStudio.TestTools.UnitTesting; using...

Serialize poco containing object property into Json

c#,xml,serialization,json.net,poco
I have a class that I need to serialize to pass to another system. The class contains a property that is defined as an object, because the type of class the object will contain can vary at runtime. My classes looks something like this simplified mock up; public class MyTestXML...

Newtonsoft Json Deserlize as C# Datagridview

c#,json,datagridview,json.net
I have some issues using the Newtonsoft Json Plugin. I want to fill a datagridview using Json but dont know how. In the Documentation of Newtonsoft Json i get an exmaple with datatable but if i try this sample i just get Errors. This is my Json: [ { "id":...

why do we need to prevent Circular Object References

json.net,xmlserializer,datacontractserializer,serializer
I'm new to this. Can you please explain to me why the "Circular REference" is a bad thing, what's the bad result it may bring about?

Valid JSON but Cannot Deserialize

c#,json,json.net
I want to do something like... Dictionary<string, string> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonstring); And I have valid data like below, but it won't deserialize it properly. Can someone tell me what I did wrong? [ { "Shop": "101", "Table": "hro", "ROWGuid": "031a0762-8d50-4d7c-9da9-9a233962733e", "JSONData": [ { "BOXFER": false, "RO_NO": "0423684", "CUST_NO": "9902215",...

Change property value while converting from XML to JSON

c#,json.net
In a project I'm getting some data from DB using TSQL FOR XML. In all tables the minimun value for Date fields is set to 01/01/1900. That's because null values are not permitted as an internal politic that cannot be changed. With the xml result I need to convert it...

Trying to Parse JSON in C# using JSON.NET

c#,json,json.net
I'm trying to parse some JSON using JSON.NET but whenever I try to get the value from any of the values, it returns 0. I just want to get the values from the first set of data. Here is my code: string text = listBox1.SelectedItem.ToString(); text = text.Substring(text.LastIndexOf(": ") +...

how to retrieve data from Json file and displaying it in HTML dropdown…?

javascript,json,angularjs,json.net
Hi i have developed simple Html Page using AngularJS which displays Manufacturer Name in drop down on user selection correspondent Manufacturer Id will get displayed in the below text box. I have used ng-repeat directive to display manufacturer names in HTML Dropdown and ng-model directive to display selected manufacturer Id....

Deserialize a JSON object with Ref property

c#,json,github,json.net
I'm trying to deserialize the JSON that gets posted from GitHubs webhook for a push event. It uses a "ref" property to store the branch information, but ref is a reserved word in C# so the serialization isn't working. Right now I have public class PushEvent { [JsonProperty("ref")] public string...

Android accessing JSONObject

java,android,arrays,json,json.net
I'm new to JSONObject, However I'm able to decode simple json format. I have new kind of JSONobject. How do I access each and every elements ? Image : Thanks!...

Can I serialize nested properties to my class in one operation with Json.net?

c#,multithreading,json.net
Lets say I have a model like: public class MyModel { public string Name { get; set; } public string[] Size { get; set; } public string Weight { get; set; } } And Json like this: { "name" : "widget", "details" : { "size" : [ "XL","M","S", ] "weight"...

Serialize byte array in JSON.NET without $type

c#,json,serialization,json.net
I would like to serialize all my contract with $type reference using TypeNameHandling.Objects. However when using this flag, all byte arrays (byte[]) are serialized using $value+$type. I still want Base64 encoding but without $type. For example, for the following contract: class MyClass { public byte[] MyBinaryProperty {get;set;} } I get:...

How configure json.net deserializer to track missing properties

c#,json.net
Semple class: public class ClassA { public int Id { get; set; } public string SomeString { get; set; } public int? SomeInt { get; set; } } Default deserializer var myObject = JsonConvert.DeserializeObject<ClassA>(str); creates the same object for two different inputs {"Id":5} or {"Id":5,"SomeString":null,"SomeInt":null} How can I track properties...

REST API response standards: Timezone

rest,asp.net-web-api,timezone,json.net,asp.net-web-api2
Is there any ISO standard for how we should return a timezone in a REST API? If I return a TimeZone type from a ASP.NET WebApi 2 action, the framework serialises the response model to look like this: { "Id": "Dateline Standard Time", "DisplayName": "(UTC-12:00) International Date Line West", "StandardName":...

Deserialize malformed JSON with JSON.NET [duplicate]

c#,json.net
This question already has an answer here: How can I parse a JSON string that would cause illegal C# identifiers? 2 answers I have a snippet of JSON that looks like this: {"123":{"name":"test","info":"abc"}} The 123 is an ID and can change on each request. This is beyond my control....

parsing JSON with Json.Net to get the Key

c#,json,json.net
Searched my question and didnt find the answer, I have a JSON file like below: { "handle":"ABCD", "Tracks":{ "Design":{ "rating":402 }, "Development":{ "rating":1584, "reliability":"n/a" }, "Specification":{ "rating":923, "reliability":"0.13" }, "Conceptualization":{ "rating":895 } } } I am getting a dynamic object of json: dynamic dynObj; dynObj = JsonConvert.DeserializeObject(content); how can I...

How do you Add or Update a JProperty Value in a JObject

c#,json,json.net
I am currently using the following extension method to perform this task, but it almost seems like there should be some existing included method or extension to perform this (or at least a subset of this). If there isn't anything within Json.NET then what is the recommended process, or how...

Deserialize Json - Object of objects

c#,json,json.net,deserialization,json-deserialization
I have some JSON being sent to me that looks like this: {"MessageCodes": { "Code1": "Message 1", "Code2": "Message 2", "Code3": "Message 3", "Code4": "Message 4", "Code5": "Message 5", "Code6": "Message 6", }} This is saying there is an object called MessageCodes which contains many other objects within it (Code1,...

JSON DeserializeObject error for a string and an object (array)

json.net
This is my JSON value { "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "candidates": [ { "address": "380 New York St, Redlands, California, 92373", "location": { "x": -117.19564110200449, "y": 34.057084093752607 }, "score": 99.890000000000001, "attributes": { } }, { "address": "380 New York St, Redlands, California, 92373", "location": { "x": -117.19564235064003,...

JProperty.WriteTo with collections in a JsonConverter

c#,json,json.net
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...

Need to parse this data with Json.NET

c#,xamarin,json.net
Here is a string named responseString I get from server. If I use Console.Write(responseString) I get the following output { "success": true, "info": "Logged in :) ", "data": { "authentication_token": "iexGFwJ6HwERQZ3wJ4NG" } } The problem is that I need the value of the key "authentication_token". How can I achieve that?...

How do I use JObject if the names are slightly different?

javascript,c#,json,model-view-controller,json.net
I have a JObject from JSON.NET with the following: var jOBject = {"schedule.ID" : 1, "schedule.Name" : "NameSchedule"} The above is what I get from using Javascript to return the ID's and values of textboxes in the MVC Form in my View. In my controller using C#, I would like...

Web API translating input into random int

c#,post,asp.net-web-api,json.net
not sure whether the subject is the best description for this problem but I am getting an unusual problem where I have a single Web API operation and a single field on a request and for some odd reason the value gets manipulated. Depending on the input this gets converted...

Deserialize RestResponse to JSON data

c#,json.net
how to deserialize the below Rest response to JSON response my rest response is in the format { "new_token":"fdffdsfdsfdsf", "expires_in":400, "login_type":"abc" } I have a POCO class as public string NewToken { get; set; } public string ExpiresIn { get; set; } public string LoginType { get; set; } How...

Why does the DeserializeXmlNode output XML enclose array elements in an extra tag?

json,xml,json.net,deserialization
I have the following JSON I am converting to XML: { "root": { "object": [{ "Name": "Cust1", "addresses": [ [{ "AddressLine1": "Address1", "AddressLine2": "Address2" }], [{ "AddressLine1": "Address3", "AddressLine2": "Address4" }] ] }, { "Name": "Cust2", "addresses": [ [{ "AddressLine1": "Address1_2", "AddressLine2": "Address2_2" }], [{ "AddressLine1": "Address3_2", "AddressLine2": "Address4_2" }]...

how to create JSON array in C# using JSON.NET

c#,json.net
How to create JSON in C# so that we can display pass as array to highchart. [ { y : 3, myData : 'firstPoint' }, { y : 7, myData : 'secondPoint' }, { y : 1, myData : 'thirdPoint' } ] ...

Issues parsing a 1GB json file using JSON.NET

json,parsing,stream,json.net,large-object-heap
I have gotten an application where the input has been scaled up from 50K location records to 1.1 Million location records. This has caused serious issues as the entire file was previously de-serialized into a single object. The size of the object is ~1GB for a production like file with...

Postgres json_agg includes column header - Incorrect JSON?

c#,json,postgresql,json.net
Follwoing this post, I have a SQL query that returns the following table: team (json) "{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}" "{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}" I need to aggregate this into JSON to use in my app. I'm using the following: SELECT json_agg(u) FROM (SELECT DISTINCT ON (t.team->>'Name') t.team FROM matches m, json_array_elements(m.match->'Teams') t(team) ORDER BY t.team->>'Name', m.id...

json.net map elements to collection

c#,json.net
I get a json object that looks like the following. { "result": { "status": 1, "teams": [ { "team_id": 1838315, "name": "Team Secret", "tag": "Secret", "time_created": 1408993713, "rating": "inactive", "logo": 543025270456493060, "logo_sponsor": 540768028333677400, "country_code": "", "url": "http://www.teamsecret.gg/", "games_played_with_current_roster": 0, "player_0_account_id": 41231571, "player_1_account_id": 73562326, "player_2_account_id": 82262664, "player_3_account_id": 86745912, "player_4_account_id": 87278757, "admin_account_id":...

Converting Json object to DataTable

c#,datatable,json.net
In a few posts here and also on other forums I have found this code quoted for turning a Json object into a DataTable: DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable))); I can't get this to work. It always throws a JsonSerializationException. Am I missing something? This is simple example to show...

Deserialize with Json.Net fails on some fields

c#,json,json.net,deserialization
I try to deserialze Json into a c# object using Json.Net. c# class: public class Evaluation { [DataMember(Name = "id")] public int Id { get; set; } [DataMember(Name = "avg")] public string Average { get; set; } [DataMember(Name = "median")] public string Median { get; set; } [DataMember(Name = "teacherID")]...

Could not create an instance of type X. Type is an interface or abstract class and cannot be instantiated

c#,json.net
Using version 7.0.1 Beta3, I'm trying to serialize/deserialize a complex POCO with properties that are arrays of abstract classes. These arrays could contain instance of classes that are derived from abstract ones. At serialization, everything seems OK. The Json fragment below shows that the type information is set correctly. The...

Newtonsoft inline formatting for subelement while serializing

c#,json.net,nsjsonserialization
Is it possible to create an attribute to serialize some subelements inline (Formatting.None) with newtonsoft json.net? I have a very huge set of data and I want to keep it readeable. Some subelements are not very important and can be writen inline. { "name": "xxx", "desc": "xxx", "subelem": [ {"val1":...

How to serialize static properties in JSON.NET without adding [JsonProperty] attribute

c#,json.net
Is it possible to serialize static properties with JSON.NET without adding [JsonProperty] attribute to each property. Example class: public class Settings { public static int IntSetting { get; set; } public static string StrSetting { get; set; } static Settings() { IntSetting = 5; StrSetting = "Test str"; } }...

Results from C# JSON-Deserialization to String

c#,json,json.net
I used json2csharp to generate functions and classes but I am a bloody newbie. What I want is using the Data from the JSON Array and display it in a Textbox. Here is the Code: public class Sent_SMS { public string status { get; set; } public string error {...

JSON.Net to serialize/deserialize struct to string

c#,json,struct,json.net
I have a c# struct that is used as dictionary key. In order to make that dictionary convert to json I need struct serialized to string (like json.net does for built in structs). public struct CreditRating { public CreditRating(string json) : this() { var levels = json.Split(new[] { '~' },...

Escaping quotes in Newtonsoft JSON

c#,asp.net-mvc,razor,json.net
I've an object: public class Test { public string Prop1 { get; set; } } I'd like to serialize it to json in a view, so in my cshtml: <script type="text/javascript"> var myJson = JSON.parse('@Html.Raw(JsonConvert.Serialize(Model.MyTest))'); </script> It works, until Prop1 contains quotes, because it gets rendered as: var myJson =...

Querying JSON with JSONPath or SelectTokens? With JSON.NET in C#

json,json.net,querying
I am trying to use the Newtonsoft.Json.Net in c#. The following is part of JSON file that I need to retrieve data out of: "video": { "local_recording_device": { "codecs": null }, "preferred_string": "___PREFERRED___", "streams": { "99176901": { "id": "99176901", "name": "PTZ Camera", "site": "someone", "email": "[email protected]", "codec": "VP8 HD1 (720p)",...

Can't parse JSON object with Newtonsoft.JSON

c#,json,json.net
I have a problem with parsing following JSON object: {     "SERVER1/DeviceIpint.3/SourceEndpoint.video:0:0" :     {         "origin" : "SERVER1/DeviceIpint.3/SourceEndpoint.video:0:0",         "state" : "connected",         "friendlyNameLong" : "Camera 3",         "friendlyNameShort" : "3" }, "SERVER2/DeviceIpint.5/SourceEndpoint.video:0:0" :...

JSON.NET Parsing Full Key-Value Pair as Key

c#,json,json.net,asp.net-web-api2,custom-attributes
I'm rolling my own ValidateAntiForgeryToken attribute for Web API 2.2 for one of my controllers that processes form data through AJAX calls. I'm sending the data to my controller as JSON and it looks like this (pulled from Fiddler): {"__RequestVerificationToken":"E8EoBCaFbqSOXhQZiuM93jciTcOAYeLjZj682-3SZRaQ6OOtrm-caZI_IWnX1FH_nwe_AuWnWwxy5ulS0Ynz0STlNptqN09Lu69HxyTeA9PUln8h73yjahB24QPxqI010","ProjectInfo.Description":"Test Description 2"} I was trying to get the __RequestVerificationToken data...

Deserialising mimekit.MimeMessage Object

c#,json,json.net,mimekit
I am having some issues deserialising a mimeKit.mimeMessage that I serialised to a JSON string and stored in a redis key-value cache. I am able to serialise and store the mimeMessage successfully using either json.NET or Jil, however when I go to deserialise, the following error is thrown. Thrown by...

JsonConverters and object properties

json.net
I'm trying to find an answer to a problem that has stumped me for a few days, I'm converting some legacy WCF code over to SignalR, it's an internal API and the client is Silverlight for the moment. I have a .NET class (Content1) on the server side that has...

Casting error from deserialized json in c# using newton json

c#,json,serialization,casting,json.net
Unable to cast to int from deserialized json (dictionary object) Here is the code: Lets say you have dictionary object. Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("key", 1); Now i serialize & deserialize it. var serializedData = JsonConvert.SerializeObject(dict); var deserializedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedData); And getting error when i do...

Loop Mutliple JSON objects to get multiple values

c#,json,asp.net-mvc,json.net
Using JSON.Net (http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) and the following C# code: @using Newtonsoft.Json; @using Newtonsoft.Json.Linq; @{ var url = "https://graph.facebook.com/v2.2/me&fields=id%2Cname%2Cposts.limit(3)&format=json&method=get&pretty=0&suppress_http_code=1"; var syncClient = new WebClient(); var content = syncClient.DownloadString(url); JObject facebook = JObject.Parse(content); //To-Do: Loop each JSON object to get message, image, & link values. } How would I loop each JSON object...

How to displayJson Object Name/Label while returning the list of the same object type

c#,.net,json,asp.net-web-api,json.net
Here are my Class [DataContract(Name="Test")] public class Test { [DataMember] public string Name { get; set; } [DataMember] public string Type { get; set; } } [DataContract(Name="Root")] public static class Root { [DataMember(Name="TestList")] public static List<Test> TestList { get; set; } } Expected Json To be returned { "Test":[ {...

JSON.Net deserialization error setting value to property

c#,json,json.net
I want so serialize/deserialize the following model: public class ReadabilitySettings { public ReadabilitySettings() { } private bool _reababilityEnabled; public bool ReadabilityEnabled { get { return _reababilityEnabled; } set { _reababilityEnabled = value; } } private string _fontName; public string FontName { get { return _fontName; } set { _fontName =...

Deserializing a jagged array via JSON.NET with types

c#,arrays,json,serialization,json.net
So I'm trying to deserialize jagged arrays using JSON.NET. I can deserialize them with a basic object[][] just fine, but I'd like to be able to access the properties without indexers. Something like expression-bodied properties would be great. The big problem here is that these arrays are key-less. Sample of...

How to create a JSON stringwith key/value pairs of web.config appsettings?

c#,json.net
I need to loop through the app settings collection of web.config and create as key value pairs in JSON string. I am using JSON.Net. How can I prepare a JSON string inside the for loop? Thank you! foreach (string key in ConfigurationManager.AppSettings) { string value = ConfigurationManager.AppSettings[key]; } ...

JSON.NET: Deserializing from JSON with LINQ

javascript,c#,json,json.net
I have following json: {[ "{\"Id\":3,\"ParentName\":\"TicketController\",\"ChildName\":null,\"Body\":\"Ticket\",\"ParentId\":null,\"HasChildren\":true,\"imageUrl\":null}", "{\"Id\":0,\"ParentName\":\"TicketController\",\"ChildName\":\"MainPage\",\"Body\":\"HomePage\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}", "{\"Id\":1,\"ParentName\":\"TicketController\",\"ChildName\":\"TicketList\",\"Body\":\"Requests\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",...

Timezone offset ignored

c#,datetime,asp.net-web-api,json.net
When the following setter receives endDate="2015-05-01T00:00:00+08:00" in a json string, the time zone offset is lost and the value is 2015-05-01T00:00:00. I need the date to adjust to UTC when the offset is lost. The object is deserialized automatically within a WebAPI Formatter using JSON.NET private DateTime? _endDate; public DateTime?...

Complex json tree parsing

c#,json,json.net
So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data. { "results":[ { "id":{ "key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable", "url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=", "type":"Phone", "uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786", "durability":"Durable" }, "line_type":"Landline", "belongs_to":[ { "id":{...

Deserialize Object (Newtonsoft) with an array of arrays inside

c#,arrays,json.net
So I need to convert this string into an object essentially. { "character_list": [ { "character_id": "5428018587875812257", "name": { "first": "gixtr2", "first_lower": "gixtr2" }, "faction_id": "3", "head_id": "1", "title_id": "17", "times": { "creation": "1355333636", "creation_date": "2012-12-12 17:33:56.0", "last_save": "1385855627", "last_save_date": "2013-11-30 23:53:47.0", "last_login": "1385850955", "last_login_date": "2013-11-30 22:35:55.0", "login_count": "334", "minutes_played":...

Deserialize a json serialized CookieCollection

c#,serialization,json.net,json-deserialization,httpcookiecollection
In my code I have to Json serialize a CookieCollection object and pass it as string, to achieve this I do like this: var json = Newtonsoft.Json.JsonConvert.SerializeObject(resp.Cookies); resulting to the following json [ { "Comment": "", "CommentUri": null, "HttpOnly": false, "Discard": false, "Domain": "www.site.com", "Expired": true, "Expires": "1970-01-01T03:30:01+03:30", "Name": "version",...

Accessing subfields in json file

c#,.net,json.net
Assuming I have a JSON file with the following structure. How I can access the names of the properties in the metadata field. { "mappings": { "basedoc_12kja": { "properties": { "created": { "type": "date", "format": "dateOptionalTime" }, "customerID": { "type": "string" }, "deleted": { "type": "boolean" }, "documentID": { "type":...

Deserialize PSON file

c#,json,powershell,json.net
I have the task of de-serializing a PSON (PowerShell Object Notation) file and am struggling to get it working. Apparently the PSON file is a variant of JSON used by Puppet which encodes the strings differently - according to this source I have tried just using the standard JSON.Net DeserializeObject...

WriteJson override with JSON.NET library

c#,asp.net-web-api,json.net,asp.net-web-api2
I made a simple JsonConverter because I have a page that posts a JSON array which can be of a generic type. Posting JSON data and converting that to a typed object works fine using the overriden ReadJson method in my custom JsonConverter class. I also need to read from...

json.net insert multiple objects on post

c#,json,json.net
Hi I want to store multiple posts of jsonCallback. As it is my script works but overwrites/updates bw_results.json each time. string json = "jsonCallback(\n" + JsonConvert.SerializeObject(results, Formatting.Indented) + "\n);"; File.WriteAllText(@"C:\inetpub\wwwroot\JSON\dotNet_BW3b\bw_results.json", json); // And this my json file jsonCallback( { "bw_numbers": [ "76", "66", "44", "66", "66", "65" ], "coin": "H",...

Json.Net: Html Helper Method not regenerating

asp.net-mvc,angularjs,json.net
I'm running into a problem where an ASP.NET MVC html helper method I created is not being "regenerated" each time it is called. The purpose of the helper method is to create Javascript objects to be used in an angularjs framework. For example, here's a code snippet where the helper...

Custom JsonConverter for property: get property name

json.net
I have this sample converter for guid properties: public class CustomGuidConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof (Guid?) || objectType == typeof (Guid); } public override void WriteJson(JsonWriter writer, object oldValue, JsonSerializer serializer) { if (value != null) { var newValue = convert(oldValue);...

Building a JsonConstructor to be able to deserialize my object

c#,json,serialization,json.net,unit-class-library
I am using JSON.net and am trying to serialize and deserialize a Distance object from the opensource UnitClassLibrary. Currently, I have an object serialized as the following JSON: { "ThirtySecondsOfAnInch": 454, "SixteenthsOfAnInch": 227, "EighthsOfAnInch": 113.5, "QuartersOfAnInch": 56.75, "HalvesOfAnInch": 28.375, "Inches": 14.1875, "Feet": 1.1822916666666667, "Yards": 0.3940972222222222, "Miles": 0.00022391887626262627, "Millimeters": 360.36249999999995, "Centimeters":...

Windows Phone HttpClient GetAsync performance

c#,windows-phone-8.1,json.net,asp.net-web-api2
I'm working with twitch REST API for education purposes(MVVM pattern) on Windows Phone platform. I noticed pure performance while using HttpClient: I get a collection of 10 elements Pass it to CheckCannelStreamStatus I removed the code because it was draft for prototype. Like in the answer bellow the problem is...

Using Json.NET for JSON Model Binding

json,asp.net-mvc,json.net,model-binding
I have a method being posted to via AJAX with the following header: public JsonResult GetDocuments(string searchTerm, SortRequest sort) The SortRequest object is defined as follows: [DataContract] public class SortRequest { [DataMember(Name = "field")] public string Field { get; set; } [DataMember(Name = "dir")] public string Direction { get; set;...

HttpClient GetStreamAsync and http Status codes?

c#,stream,json.net,httpclient
I wish to use streams as recommended by the json.net performance tips documentation, however I'm unable to find how to get a hold of the http status codes without the typical awaiting the HttpResponse. Is there perhaps a way of getting the status code first without reading the data? So...

Deserialize JSON with Numeric Rows

json,json.net
I am trying to deserialize some JSON into a list using JSON.NET; however, there is a number in the way: Here is the JSON: "payment_info": { "fb_id": "", "order_items": { "0": { "product_id": "4534", "type": "product", "shipping_cost_per_item": "1.00", "quantity": "3", "price_each": "10.00", "price_total": "30.00" } }, Here is my class:...

Deserializing JSON Array with JSON.net

c#,json,windows-phone-8,windows-phone,json.net
I have some JSON from the EPA's UV Index API. The json is an array with separate elements in it. Example of the JSON: [ { "ORDER": 1, "ZIP": 19021, "DATE_TIME": "MAY/27/2015 07 AM", "UV_VALUE": 0 }, { "ORDER": 2, "ZIP": 19021, "DATE_TIME": "MAY/27/2015 08 AM", "UV_VALUE": 1 }, {...

Attempting to deserialize an object using JSON.NET in Windows 10 Universal App fails with FileNotFoundException

c#,windows-runtime,json.net,windows-10
I'm using the Windows 10 Preview SDK, and attempting to port forward some code that depends on JSON.NET. It's failing with the following exception: {"Could not load file or assembly 'System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The system cannot find the file specified.":"System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e,...

How do I deserialize JSON.NET objects that don't have names?

c#,json,json.net
How do I deserialize the following in JSON.NET? (I want to use the strings) ["String1","String2","String3"] Do my JSON objects necessarily have to look like this? ["Name1":"Value1","Name2":"Value2","Name3":"Value3"] ...

JSON.Net parse Facebook Graph JSON for all messages

c#,asp.net-mvc,facebook-graph-api,json.net
Using JSON.Net (http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) and the following code: @using Newtonsoft.Json; @using Newtonsoft.Json.Linq; @{ var url = "https://graph.facebook.com/v2.2/me&fields=id%2Cname%2Cposts.limit(3)&format=json&method=get&pretty=0&suppress_http_code=1"; var syncClient = new WebClient(); var content = syncClient.DownloadString(url); JObject facebook = JObject.Parse(content); //To-Do: Get all messages as list<string> using LINQ for JSON // Ex: IList<string> allDrives =...

serialization c# object collection, how to get just certain property of references object?

json.net,json-deserialization
this is the class: public class Category { public guid id, public string name, public Category Parent } i am using Json.net to serialize a collection of it, but i don't want the Parent object to be serialized, just need the id: what i expecte: [ {'name':'cate1','id':1000,'parent':999} {'name':'cate2','id':1001,'parent':998} ] i...

Deserialize object using JSON.NET, but put some properties into a member of the class

c#,json,serialization,json.net
I am writing a set of data structures to ingest third-party JSON into (no writing out) using JSON.NET. I have a case for reading some of the top-level JSON elements into a member object of the object being deserialized into. My JSON: { "Id":1 "Checksum":42 "Name":"adam", "Hair":true } My ideal...

Deserializing Json String into multiple Object types

c#,json,serialization,json.net
I have a Json String that I get from a web service; it has a list of collections, each collection represents an object, for example: [ // Root List [ // First Collection : Team Object { "id": 1, "team_name": "Equipe Saidi", "is_active": true, "last_localisation_date": "2015-05-06T13:33:15+02:00" }, { "id": 3,...

Deserializing JSON to flattened class

json,json.net,deserialization
I found the same question here... Deserializing nested JSON structure to a flattened class with Json.NET using annotations ...but without a proper answer. One of the best suggestion is to wrap the nested object in a new class but this approach introduces another issue: lego name. In my example the...

Convert string[] of json object to List

c#,arrays,json,json.net
I am using json.net for json object parsing. I have a string array that has of Json objects. so instead of 1 string with Json Array, I have each json object on different index of string array. I need to de-serialize this string[] of json object into List<T>. If it...

Getting element name in a JSON file

c#,.net,json.net
I have a given JSON file (json): { "people":{ "name":{ "Senior":{ "name": "Jan", "country": "US" }, "Junior":{ "name": "George", "country": "CA" } } } } This is made after a example of the Local State file found in C:\Users\username\Local\Google\Chrome\User Data\Local State I want the output like this: Senior Name: Jan...

Flattening nested JSON object in JSON.NET

c#,json.net
I have a simple JSON like this: { "id": 123, "name": "BaseName", "variation": { "name": "VariationName" } } Is there a simple way to map it with JSON.NET deserialization to: class Product { public int Id { get; set; } public string Name { get; set; } public string VariationName...

How to Convert Custom Attribute into Json String

json.net
Is there any way to convert any of my custom attribute(s) into something when I call the JsonConvert.SerializeObject(...) function? For example, I have a class: class A { [UnitAttribute("---")] public double? Ratio { get; set; } } When serialize any instance of such class, is there any way to put...

Custom JSON Derivative Format

c#,.net,json,json.net
I would like to have a serialization format that is nearly identical to JSON, except that key-values are represented as <key>="<value>" instead of "<key>":"<value>". With Newtonsoft I made a custom JsonConverter called TsonConverter that works fairly well, except that it can't "see" an embedded dictionary. Given the following type: public...

Json.NET Deserialization into dynamic object with referencing

c#,dynamic,json.net
How can I get Json.NET to deserialize into dynamic objects but still do reference resolution? dynamic d=JsonConvert.DeserializeObject<ExpandoObject>(...) just as dynamic d=JsonConvert.DeserializeObject(...) returns a dynamic object but they don't resolve the $ref and $id parts. (An ExpandoObject eo for example will only have eo["$ref"]="..." and doesn't have the properties it should...

how to retrieve blob data from Azure blob in Json format?

json,azure,json.net,azure-storage-blobs
I have stored json data format in azure blob storage, Now want to retrieve that data from azure blob in the form of json. I tried like following //get all blob from contrainer var storageAccount = CloudStorageAccount.Parse("connection string"); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("tablesblob"); foreach (IListBlobItem item in...

Foreach bind items to Datatable with C# and JSON

c#,asp.net,json.net,repeater
DataTable dtInventory = new DataTable(); dtInventory.Columns.Add("ItemID", typeof(string)); dtInventory.Columns.Add("ItemImageUrl", typeof(string)); dtInventory.Columns.Add("ItemName", typeof(string)); dtInventory.Columns.Add("Tradeable", typeof(string)); string json = new WebClient().DownloadString("storeJSON.txt"); JToken jsonInventory = JToken.Parse(json); JObject jsonItemData = jsonInventory["StoreData"].Value<JObject>(); foreach (JProperty jItemID in jsonItemData.Properties()) { string sItemID =...

Value cannot be null when deserializing JSON

c#,winforms,json.net
I have a db table which has column in which content is stored in JSON format, I am retrieving JSON but I am getting this error. Value cannot be null Here is my code snippet. var stuff = (JObject)JsonConvert.DeserializeObject(commentId); string name = stuff["Name"].Value<string>(); string email = stuff["Email"].Value<string>(); string company =...

Problems with handling Dictionary in JObject (Newtonsoft.Json)

c#,json.net
I have this json object. { "Apparel":[ "Athlete", 73 ], "Freeze":[ "Coin", 19, "Fur", 37, "Grade", 72 ], "Lobster":[ "Node", 18 ] } I read it in a string and convert it to a JObject like this: using Newtonsoft.Json; using Newtonsoft.Json.Linq; JObject myobj = JObject.Parse(mystr); How should I go about...

How to convert json with jarray inside to a object

c#,json,json.net
I have the following classes public class Test { public string name; public List<Field> fields; } public class Field { public string id; public string name; } and the following Json { "name": "name1", "fields": [ { "id": "4786182461", "name": "field1", }, { "id": "41241241122", "name": "field2", }, ] }...

How to convert this JSON to a datatable?

c#,.net,json,asynchronous,json.net
[ [ "<div id=\"status\" style=\"width:20px; height:20px; \" class=\"circle red\"></div>", "<a runat=\"server\" id=\"link0\" href=\"MachineDetails.aspx?PageName=PCsByLocation.aspx&MachineName=AUBDW012\">AUBDW012</>", "Dye, Paul", "", "AsiaPacific / Australia / BrisbaneDistribution", "<div id=\"divonoffswitch\" class=\"onoffswitch\"><input type=\"checkbox\" name=\"onoffswitch\"...