Questions tagged [json.net]

1

votes
2

answer
523

Views

Azure CloudBlobStream serialization (with Json.NET)

I have a little problem. My environment is a console app in .NET Core 2.1. Look at the this code: private static void Main(string[] args) { try { Console.WriteLine($'Test starts: {DateTime.Now.ToString('o')}'); string connectionString = '[My connection string]'; string containerName = 'mycontainer';...
Attilio Gelosa
3

votes
3

answer
52

Views

Return different object types in case statement?

How can I return different object types in my case statement? public object?? CreateObjectType(JToken token) { switch (token['type'].Value()) { case 'Car': var Car = new Car(); return car; case 'Boat': var boat = new Boat(); return boat; ..... } } Do I need to create an abstract/interface class to...
Mask-dCodex
0

votes
0

answer
13

Views

HttpClient - An existing connection was forcibly closed by the remote host - IIS Published web app

I have tried a ton of solutions that I searched about this issue, but none of them fixed my web app. So, I have a web app that uses a vendor API to populate my data. I was able to successfully connect to the API and transact different kinds of API calls locally. After I completed my web app, I trie...
Lex
0

votes
1

answer
15

Views

Newtonsoft.Json filtering output [duplicate]

This question already has an answer here: Filtering collections in C# 9 answers How would I filter the output (Console.WriteLine(statusCollection...) to only show results if s.Service_name equals 'cloud_networking' in the past 24hrs (s.Begin date is formatted like this 2018-05-19T04:39:59Z class Pr...
acctman
1

votes
1

answer
58

Views

Json Deserialise return null when convert to list of object in c# [duplicate]

This question already has an answer here: Private setters in Json.Net 3 answers I am trying to deserialise the json into custom class list using Newtonsoft.Json. Here is my code: public List getEmployee() { string Baseurl = 'http://dummy.restapiexample.com/api/v1/'; using (var client = new HttpCli...
1

votes
3

answer
44

Views

Newtonsoft JSON DefaultSettings per Assembly

In order to automatically trim all input strings and remove new lines, I developed an implementation of JsonConverter and registered it in Startup with JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = new List { new StringTrimmer() } }; This works, but the string trimme...
Dave
1

votes
1

answer
566

Views

JSON Schema to C#

I am looking for a class or tool to convert JSON schema into a C# class as a prebuild step. I have found several 'home-brew' solutions (jsonschema.net, NJsonSchema, ...) , but would prefer to use some mature / official code related to a company / project. I understand that the Newtonsoft.json.Schema...
Stiefel
1

votes
0

answer
130

Views

ModelState validation fails for dictionary where keys are enums

I have a model that has the following property: [JsonConverter(typeof(MapConvertor))] [IsValidSomeObject] public Dictionary SomeMap { get; set; } And I created the following custom ValidationAttribute class to validate it: public class IsValidSomeObjectAttribute : ValidationAttribute { protected ove...
Apha
1

votes
0

answer
338

Views

Serialize enum to string with RestSharpJsonNetSerializer [duplicate]

This question already has an answer here: Why serializing Version with JsonPropertyAttribute doesn't work? 1 answer parsing an enumeration in JSON.net 1 answer How to tell Json.Net globally to apply the StringEnumConverter to all enums 5 answers I have my RestSharpJsonNetSerializer class below. I...
Razkar
1

votes
4

answer
243

Views

Json.net - Parse array with unknown property name

How can I select a property from a nested array when the name is not know at development time. For example if I wanted to get the name 'SamsClub' from the 'Store' array but did not want to hardcode the array name because there can be n number of arrays. ['sections']['Store']['name'] Sample Json { 'l...
Gearbolt
1

votes
1

answer
204

Views

Treating error on deserializing json

My problem basically is this: I have an output from an API that returns a json with one element called 'error' with any message. When I'm trying to deserialize my object and the server returns me an error, I get this json rather than my json object (product, orders...). This is the code where happe...
thatsallfolks
1

votes
1

answer
255

Views

Deserialize Json and store part of it into list of objects

How can I deserialize this Json and hold all the Datafield and HeaderText in List of SampleClass public class SampleClass { public string Datafield { get; set; } public string HeaderText { get; set; } } { 'SummaryResults': { 'ControlType': 'Table', 'ColumnDefinitions': [ { 'Datafield': 'SourceSystem...
venkatesh
1

votes
2

answer
591

Views

How to remove circular reference from entity framework core

Web Api Core, Entity Framework Core Situation - Many to many relationship. A, Join, B. Join has Id references to both A and B. A has collection for Joins. B has collection for Joins. Goal - Get A with Joins with B - and no further. Problem - I get A with Joins with B with the same singular Join...
user1904662
1

votes
4

answer
333

Views

Newtonsoft JSON Deserialize to object list in list

I have to deserialize a json string to my own object which has a list of childs and this has also a list of childs. Like this: parent class -> list -> list How is it possible to desserialize this json string ? json example: { { 'Departementstructure': { 'org.MainDepartments': [{ '@MainDepartmentsId...
floho
1

votes
1

answer
202

Views

Return JSON from MongoDb without $date

I am using MongoDb with C# in a WebApi app. My data does not lend well to mapped data types due to the dynamic nature of the document stored. For example, here is an example of some data. Note the Data section with values that can either be arrays or a single string (Technician): { '_id' : '5a59129d...
dprice
55

votes
9

answer
46.5k

Views

Deserialize collection of interface-instances?

I would like to serialize this code via json.net: public interface ITestInterface { string Guid {get;set;} } public class TestClassThatImplementsTestInterface1 { public string Guid { get;set; } } public class TestClassThatImplementsTestInterface2 { public string Guid { get;set; } } public class Clas...
user1130329
1

votes
1

answer
42

Views

JsonConvert within Quartz.net job failing

I have a windows service that utilizes quartz.net to compares accounts in 2 different systems on a schedule and syncs the changes from one to the other. I can not seem to get a simple rest call to work because serializing the json is failing. No exception is thrown but the json string is empty. priv...
Christopher Kelly
1

votes
1

answer
55

Views

ArangoDB - Exception in JsonTextReader.ParseValue() when inserting Large document to Remote Server

I have two instances of ArangoDB running, one on a remote/cloud server and one on a local server. Both instances are accessible and I can insert/query data on both instances. I have a document that contains an array 56,000+ doubles and when I try to insert this document to the remote server, I get a...
TimF
1

votes
1

answer
131

Views

Json.NET LINQ query for single JProperty on JArray of JObjects

I have a JArray with this configuration [ { 'name' : 'text', 'age' : 32 }, { 'name' : 'text2', 'age' : 33 }, ] and I want to use LINQ query to select a JArray containing JObjects with just the key value of a specified given key. For example: GetCollectionOfPropertiesByKey('name'); this would result...
xDGameStudios
1

votes
3

answer
19

Views

persist object-model to JSON

public class Portfolio { public string Name {get; set;} public Dictionary Positions {get; set;} } public class Position { public string Ticker {get; set;} public decimal Size {get; set;} } JsonConvert.SerializeObject(portfolio); will produce for example : { 'Name': 'SP500', 'Positions': { 'AOS': {...
BaltoStar
1

votes
2

answer
56

Views

Using classes for JSON serialization

All, I need some help with understanding how classes can work with vb.NET and JSON.NET. I'm completely new to this. I've tried searching for answers, but I'm probably not asking the right questions. Here's my dilemma: I have a JSON that I need to send to a REST API. { 'paInfo':[ { 'providerAccoun...
Mike C
1

votes
0

answer
247

Views

Newtonsoft.Json will not call the constructor when deserializing?

I have the following class: public class Configuration { public Color ErrorColor { get; set; } // other things } The Color struct is defined in a library I am using: public struct Color { public Color(uint rawValue) { /* ... */ } // other things } If I attempt to desterilize the following data: { 'E...
Michael Smith
1

votes
0

answer
52

Views

How to handle data type wise XML to JSON conversion by using NewtonSoft

I am using NewtonSoft namespace to convert the xml data to json. I want the json data value to preserve the data type. But, by using 'SerializeXmlNode' it is giving json data value in string. XML Data is: 1 false PokeMon go 2013-12-31T00:00:00 25.00 I am using the following code: string requestData...
Avijit Paul Poddar
1

votes
1

answer
38

Views

Strange behavior in serialized datatable with newtonsoft [duplicate]

This question already has an answer here: JSON.NET Parser *seems* to be double serializing my objects 1 answer I have a very simple datatable which I serialize into JSON using Newtonsoft DataTable dt = DBHelper.GetDataTable(value.Sql); string json = JsonConvert.SerializeObject(dt, Formatting.None);...
Leonardo Perez
1

votes
1

answer
188

Views

Json.NET and .NET Core WebApi - Prevent string values from being persisted in process memory

I have an API written in .NET Core 2.0 for dispensing JSON Web Tokens (JWTs). This is done via a POST request with a very simple model. public class TokenRequest { public string Username { get; set; } public string Password { get; set; } } The particulars of the API aren't important -- the goal here...
Jason E
1

votes
1

answer
1.3k

Views

How to ignore empty arrays using JsonConvert.DeserializeObject?

I am reading in a list of objects from JSON using this call: Rootobject userInfo = JsonConvert.DeserializeObject(File.ReadAllText(strFileName)); But I get an exception Cannot deserialize the current JSON array. If one of the arrays within one of the class objects is empty. As long as there is data...
Rick Engle
1

votes
0

answer
152

Views

JSON.NET serialization of type derived from List<T> [duplicate]

This question already has an answer here: How to serialize/deserialize a custom collection with additional properties using Json.Net 4 answers How do I get json.net to serialize members of a class deriving from List? 2 answers We're switching our cache system over from a binary serializer (the one...
Mike Christensen
1

votes
0

answer
457

Views

JsonConverter for Custom Deserialization

I have implemented a custom JsonConverter to deserialize concrete classes when all we know about is the interface that is using them. given this, I have overridden the ReadJson method with the following: public class MyConverter : JsonConverter { public override bool CanConvert(Type objectType) { r...
m1nkeh
1

votes
1

answer
193

Views

Configure that Newtonsoft serializer serializes a date respecting the local time

I send javascript dates to the server via: let start = new Date().toISOString() This date string is sent as UTC date string. On server side I have convert this utc date everywhere to the local date (CH/DE/AT) via myDate.ToLocalTime() which I want to save in the database. I do not want this manual co...
Pascal
1

votes
1

answer
358

Views

Metadata file 'Newtonsoft.Json.dll' could not be found

I have a console application that I am attempting to deploy to an Azure VM (Windows Server 2012R2). The console application creates a CSharp compilier instance and processes C# scripts that are sent to it. CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters options = new Compi...
webworm
1

votes
0

answer
626

Views

dotnet core 2: Serializing delegates is not supported on this platform

I am trying to pass the scope (or this) to my custom exception and show it gracefully. My code was working until I added the scope property to the custom exception. I see others have encountered this issue (link1, link2, link3) but no solution. Any solution or workaround would be appreciated. Thank...
Node.JS
1

votes
0

answer
45

Views

Access to byte stream while deserializing JSON

I've been trying to find a mechanism to provide access to the raw json while deserialising a field in json.net. My class is something like this: public class Message { public Signature Signature { get; set; } public string Payload { get; set; } } This currently gets serialised to: { '$type': 'Signed...
Adrian Lyons
1

votes
0

answer
968

Views

Upgrading Newtonsoft.Json from 10.0.3 to 11.0.1

I have just used the NuGet Package Manager to see what updates are available and it informed be about 10.0.3 - 11.0.1: I understand that a main version number change can be code breaking. How can I ascertain the issues I will have if I upgrade the package? I could not see any information. I see simi...
Andrew Truckle
1

votes
2

answer
133

Views

How to deserialize json objects to specific objects in Restsharp/Json.net on Xamarin Forms

I am using Xamarin forms and fetching a list of JSON objects, which are of multiple Types. E.g. class BaseClass { public int Id; } class ClassA: BaseClass { public string Name; } class ClassB: BaseClass { public DateTime DateOfBirth; } and so on.. When I fetch such objects (ClassA, ClassB, ...), I u...
bit
1

votes
1

answer
230

Views

JSON SelectToken Path Either Too High (Parent) or Too Low (Child) For Values I Want

I'm querying the DellAPI at https://sandbox.api.dell.com/support/assetinfo/v4/ to get the end date of extended onsite support warranties as a .NET object. But I'm having trouble defining my SelectToken path to work with the JSON result from Dell. Here's the relevant bit of code I'm using (sans the d...
CyborgHobbit
1

votes
0

answer
296

Views

Deserializing JSON child object values into parent object using JsonConvert.DeserializeObject<T> using nested converters

I'm receiving some oddly formatted JSON that I want to store in a single object. It looks something like this: { 'parentObject': { 'id': 123456, 'pointlessChildObject': { 'stringThatCouldBeStoredInParent': 'test', 'epochTimeThatCouldBeStoredInParent': '1520452800' } } } At first, I thought this wo...
RBeaulieu
1

votes
1

answer
264

Views

Deserialize JSON with varying element names

I'm struggling deserializing an json into an vb.net object with newtonsoft. The problem is, that the element name of the following array is different for each array: { 'ABC': [{ 'key': '123', 'md5sum': 'e24cb0e730269e419f036a10dd6c38d0', 'entity_metadata': { 'document_index_end': ['3162'], 'document...
Martin
1

votes
0

answer
47

Views

JsonExtensionData create custom extension data

I all, I facing a problem where I cannot annotate the model with using newtonsoft [JsonExtensionData] without the annotation the result is : { Prop1: value1, Prop2: value2, Prop3: { Key1: valuekey1, key2: valuekey2, } } but a need it to be: { Prop1: value1, Prop2: value2, Key1: valuekey1, key2: valu...
LEspera
1

votes
2

answer
80

Views

Validating JSON in a stream

I have (potentially large) json files being uploaded that need to be written out somewhere else. I would like to do at least some basic validation (for example, make sure they are valid JSON - maybe even apply a schema) but I'd like to avoid having to load the entire (again, potentially large) file...
Matt Burland
1

votes
1

answer
1.2k

Views

Mapping multiple property names to the same field in Newtonsoft.JSON

I have two components in a distributed system, which send messages which are serialized/deserialized using Newtonsoft.JSON (JSON.Net). The message properties are currently sent in Norwegian, and I am looking to translate the codebase to English. Since there is a change that some messages would ha...
Karl Cassar

View additional questions