Remove Json Object in Json Array in c# - c#

I am really new to c# language programming and
I have a JSON string:
{
"Type": "Name",
"parameters": [
{
"A": {
"type": "string",
"defaultValue": "key"
},
"B": {
"type": "string",
"defaultValue": "key"
},
"C": {
"type": "string",
"defaultValue": "key"
},
"D": {
"type": "string",
"defaultValue": "autogenerated"
},
"E": {
"type": "string",
"defaultValue": "autogenerated"
},
"F": {
"type": "dropdown",
"dropDownItems": [
"true",
"false"
],
"defaultValue": "false"
}
}
]
}
and I want to output the JSON array parameters but without "A", "B" and "C".
This JSON File is always changing but it always have this "A", "B" and "C".

Among with the answer of Thierry Prost
namespace Testedouble
{
class Program
{
static void Main(string[] args)
{
var jsonString = #"{
'Type': 'Name',
'parameters': [
{
'A': {
'type': 'string',
'defaultValue': 'key'
},
'B': {
'type': 'string',
'defaultValue': 'key'
},
'C': {
'type': 'string',
'defaultValue': 'key'
},
'D': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'E': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'F': {
'type': 'dropdown',
'dropDownItems': [
'true',
'false'
],
'defaultValue': 'false'
}
}
]
}";
var values = JsonConvert.DeserializeObject<Foo>(jsonString);
foreach (var key in new string[] { "A", "B", "C" })
{
foreach (var item in values.parameters)
{
item.Remove(key);
}
}
Console.WriteLine(JsonConvert.SerializeObject(values));
}
public class Foo
{
public string Type { get; set; }
public List<Dictionary<string, object>> Parameters { get; set; }
}
}
}

I made a small console application that shows the desired result. The flow is as follows:
We create the C# classes we need for the given JSON: DropdownInfo, ParameterInfo, ParameterBase, Base. I made them several so you can better extend them as you need.
We Deserialize the Object and then modify it the way we want.
var itemsToRemove = new string[] { "A", "B", "C" };
Here we add all the elements, which we don't want to be in the output. In our case, we remove A, B, C
- Serialize back the Object to JSON. We use Formatting.Indented, so the result looks better (beautifier, human readable)
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace JsonExercise
{
public class JsonExercise
{
public static void Main(string[] args)
{
var sb = new StringBuilder();
var line = string.Empty;
while (!string.IsNullOrWhiteSpace((line = Console.ReadLine())))
{
sb.AppendLine(line);
}
var json = sb.ToString().Trim();
var inputObj = JsonConvert.DeserializeObject<Base>(json);
var resultObj = new
{
Type = inputObj.Type,
Parameters = new List<object>()
};
Console.WriteLine("--------------------------------");
//Here we can give all the Properties, which will be skipped!
var itemsToRemove = new string[] { "A", "B", "C" };
var propertiesToAdd = new Dictionary<string, object>();
foreach (var propertyInfo in typeof(ParameterBase).GetProperties())
{
if (!itemsToRemove.Contains(propertyInfo.Name))
{
var propertyValue = (inputObj.Parameters[0]).GetType().GetProperty(propertyInfo.Name).GetValue(inputObj.Parameters[0]);
propertiesToAdd.Add($"{propertyInfo.Name}", propertyValue);
}
}
var objToAdd = GetDynamicObject(propertiesToAdd);
resultObj.Parameters.Add(objToAdd);
Console.WriteLine("Serializing Object");
Console.WriteLine(JsonConvert.SerializeObject(resultObj, Formatting.Indented));
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
public class Base
{
public string Type { get; set; }
public ParameterBase[] Parameters { get; set; }
}
public class ParameterBase
{
public ParameterInfo A { get; set; }
public ParameterInfo B { get; set; }
public ParameterInfo C { get; set; }
public ParameterInfo D { get; set; }
public ParameterInfo E { get; set; }
public DropdownInfo F { get; set; }
}
public class ParameterInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
}
public class DropdownInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
public string[] DropDownItems { get; set; }
}
}
The first part of the code with the StringBuilder class is just to read the input(The given JSON).
I will give sample input and output JSON data.
--INPUT--
{
"Type": "Name",
"parameters": [
{
"A": {
"type": "string",
"defaultValue": "key"
},
"B": {
"type": "string",
"defaultValue": "key"
},
"C": {
"type": "string",
"defaultValue": "key"
},
"D": {
"type": "string",
"defaultValue": "autogenerated"
},
"E": {
"type": "string",
"defaultValue": "autogenerated"
},
"F": {
"type": "dropdown",
"dropDownItems": [
"true",
"false"
],
"defaultValue": "false"
}
}
]
}
--OUTPUT--
{
"Type": "Name",
"Parameters": [
{
"D": {
"Type": "string",
"DefaultValue": "autogenerated"
},
"E": {
"Type": "string",
"DefaultValue": "autogenerated"
},
"F": {
"Type": "dropdown",
"DefaultValue": "false",
"DropDownItems": [
"true",
"false"
]
}
}
]
}
Edit: Changed the code after #João Paulo Amorim comment. I tested the code it works fine, use it freely.
Shout out to João Paulo Amorim and his answer. Looks smoother.
PS. My first answer on StackOverFlow \o/

With Newtonsoft.Json package:
using System;
using Newtonsoft.Json;
using System.IO;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//File with json
string jsontext = File.ReadAllText("json.json");
dynamic json = JsonConvert.DeserializeObject(jsontext);
foreach(var parameter in json.parameters)
{
Console.WriteLine(parameter.D);
Console.WriteLine(parameter.E);
Console.WriteLine(parameter.F);
}
Console.ReadLine();
}
}
}

Using newtonsoft library
Working Fiddle added
public class Foo
{
public string Type { get; set; }
[JsonProperty("parameters")]
public List<Dictionary<string, object>> Parameters { get; set; }
[JsonProperty("defaultValue")]
public string DefaultValue { get; set; }
}
var values = JsonConvert.DeserializeObject<Foo>(jsonStr);
values.Parameters = values
.Parameters
.Select(
dic => dic
.Where(kvp => new string[] { "A", "B", "C" }.Contains(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value))
.ToList();
Console.WriteLine(JsonConvert.SerializeObject(values));

1) Parse your json to JObject under namespace with using Newtonsoft.Json.Linq;
2) Retrieve 1st object inside parameters array by using JObject.SelectToken()
3) Remove A, B, C by using JObject.Remove()
string json = "Your json here";
JObject jObject = JObject.Parse(json);
JObject jObj = (JObject)jObject.SelectToken("parameters[0]");
jObj.Property("A").Remove();
jObj.Property("B").Remove();
jObj.Property("C").Remove();
string output = jObject.ToString();
Output: (From Debugger)
Online Demo

Related

convert objects model to json in c#?

I have a object model I want to show as a json string, for example:
public class SectionD
{
public string InsertID { get; set; }
public int CaseReference { get; set; }
public string AdditionalInfo { get; set; }
public DateTime CreationDate { get; set; }
}
and I want to present this as a json object, like so:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "string"
},
{
"key": "CaseReference",
"type": "int"
},
{
"key": "AdditionalInfo",
"type": "string"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
The data is being stored as a json string in a database, and I want to provide a list of fields and types to someone who would be making database views on that data.
google provides a lot of hits for querying the contents on the model, but I can't find anything for looking at the object itself.
Thanks
How about something simple like:
public class ReflectedPropertyInfo
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public class ReflectJson
{
public static string ReflectIntoJson<T>() where T : class
{
var type = typeof(T);
var className = type.Name;
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propertyList = new List<ReflectedPropertyInfo>();
foreach (var prop in props)
{
propertyList.Add(new ReflectedPropertyInfo{Key =prop.Name, Type =prop.PropertyType.Name});
}
var result = JsonConvert.SerializeObject(new {#class = className, parameters = propertyList}, Formatting.Indented);
return result;
}
}
It uses Reflection, as suggested by #dbc. After getting the type name, it gets a collection of properties and then builds up a anonymous type containing the information in the correct format, and then serializes it. The result looks like:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "String"
},
{
"key": "CaseReference",
"type": "Int32"
},
{
"key": "AdditionalInfo",
"type": "String"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
The only difference (that I see) is that it uses the actual "Int32" as the type name for integers, rather than the C# alias "int".

Removing Outer Bracket and Naming object with number?

I got really confusing with json ( I still learning about json ).
the JSON I want to:
{ "entityMap": {
"0": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"1": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"2": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"3": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
}
}
}
Is that considered bad json? And how to naming json with number like that?
This by far what I got.
{
"entityMap": [
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
}
]
}
this my class
public class editorRawTest
{
public List<entityMapItem> entityMap { get; set; }
}
public class entityMapItem
{
public string type { get; set; }
public string mutability { get; set; }
public entityMapItemData data { get; set; }
}
public class entityMapItemData
{
public string url { get; set; }
}
my execute code:
var map = new List<entityMapItem>();
var mapitem = new entityMapItem() { type = "LINK", mutability = "MUTABLE", data = new entityMapItemData() { url = "https://stackoverflow.com/" } };
map.Add(mapitem);
map.Add(mapitem);
map.Add(mapitem);
editorRawTest bc = new editorRawTest() { entityMap = map };
string JSONresult = JsonConvert.SerializeObject(bc);
string path = #"jsonmapdata.json";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(JSONresult.ToString());
tw.Close();
}
Searching through google and stackoverflow with no luck.
Any clue or help will be appreciated.
Thank you.
To get the first JSON, you would need to replace your List<entityMapItem> with a Dictionary<string, entityMapItem>, like this:
public class editorRawTest
{
public Dictionary<string, entityMapItem> entityMap { get; set; }
}
Then you would need to fill it like this:
var map = new Dictionary<string, entityMapItem>();
var mapitem = new entityMapItem() { type = "LINK", mutability = "MUTABLE", data = new entityMapItemData() { url = "https://stackoverflow.com/" } };
for (int i = 0; i < 4; i++)
{
map.Add(i.ToString(), mapitem);
}
But I would discourage you from doing that unless you have to. What you have now (the second JSON with the list) is much easier to work with. If you have a choice between the two, it is better to choose the second approach. See Using json key to store value, is it a good approach? for why.

How to deserialise JSON from HubSpot

I am having trouble deserializing JSON received from HubSpot ContactList API.
I am using Restsharp and NewtonSoft, and I'm having real struggles understanding how to correctly define the required classes in order to deserialize the JSON string, which is below:
"contacts": [
{
"vid": 2251,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2251",
"properties": {
"firstname": {
"value": "Carl"
},
"lastmodifieddate": {
"value": "1554898386040"
},
"company": {
"value": "Cygnus Project"
},
"lastname": {
"value": "Swann"
}
},
"form-submissions": [],
"identity-profiles": [
{
"vid": 2251,
"saved-at-timestamp": 1553635648634,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#cygnus.co.uk",
"timestamp": 1553635648591,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "e2345",
"timestamp": 1553635648630
}
]
}
],
"merge-audits": []
},
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
},
"identity-profiles": [
{
"vid": 2301,
"saved-at-timestamp": 1553635648733,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#khaoscontrol.com",
"timestamp": 1553635648578,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "c7f403ba",
"timestamp": 1553635648729
}
]
}
],
"merge-audits": []
}
],
"has-more": false,
"vid-offset": 2401
}
If I simply request the vid, I correctly get 2 vid's back. It's when I try to do the properties and that i get a fail.
Please help
Lets reduce the Json to the minimum to reproduce your error :
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
}
}
And the appropriate class ContactListAPI_Result:
public partial class ContactListAPI_Result
{
[JsonProperty("vid")]
public long Vid { get; set; }
[JsonProperty("portal-id")]
public long PortalId { get; set; }
[JsonProperty("is-contact")]
public bool IsContact { get; set; }
[JsonProperty("profile-url")]
public Uri ProfileUrl { get; set; }
[JsonProperty("properties")]
public Dictionary<string, Dictionary<string, string>> Properties { get; set; }
}
public partial class ContactListAPI_Result
{
public static ContactListAPI_Result FromJson(string json)
=> JsonConvert.DeserializeObject<ContactListAPI_Result>(json);
//public static ContactListAPI_Result FromJson(string json)
// => JsonConvert.DeserializeObject<ContactListAPI_Result>(json, Converter.Settings);
}
public static void toto()
{
string input = #" {
""vid"": 2301,
""portal-id"": 5532227,
""is-contact"": true,
""profile-url"": ""https://app.hubspot.com/contacts/5532227/contact/2301"",
""properties"": {
""firstname"": {
""value"": ""Carlos""
},
""lastmodifieddate"": {
""value"": ""1554886333954""
},
""company"": {
""value"": ""Khaos Control""
},
""lastname"": {
""value"": ""Swannington""
}
}
}";
var foo = ContactListAPI_Result.FromJson(input);
}
But the Value of one property will be burrow in the sub dictionary, we can the project the object in a more usefull one :
public partial class ItemDTO
{
public long Vid { get; set; }
public long PortalId { get; set; }
public bool IsContact { get; set; }
public Uri ProfileUrl { get; set; }
public Dictionary<string, string> Properties { get; set; }
}
Adding the projection to the Class:
public ItemDTO ToDTO()
{
return new ItemDTO
{
Vid = Vid,
PortalId = PortalId,
IsContact = IsContact,
ProfileUrl = ProfileUrl,
Properties =
Properties.ToDictionary(
p => p.Key,
p => p.Value["value"]
)
};
}
Usage :
var result = foo.ToDTO();
Live Demo
Creating and managing class structure for big and nested key/value pair json is tedious task
So one approach is to use JToken instead.
You can simply parse your JSON to JToken and by querying parsed object, you will easily read the data that you want without creating class structure for your json
From your post it seems you need to retrieve vid and properties from your json so try below code,
string json = "Your json here";
JToken jToken = JToken.Parse(json);
var result = jToken["contacts"].ToObject<JArray>()
.Select(x => new
{
vid = Convert.ToInt32(x["vid"]),
properties = x["properties"].ToObject<Dictionary<string, JToken>>()
.Select(y => new
{
Key = y.Key,
Value = y.Value["value"].ToString()
}).ToList()
}).ToList();
//-----------Print the result to console------------
foreach (var item in result)
{
Console.WriteLine(item.vid);
foreach (var prop in item.properties)
{
Console.WriteLine(prop.Key + " - " + prop.Value);
}
Console.WriteLine();
}
Output:

Json Array to Custom Object Mapping in C#

I have this JSON Array as input.
[
{
"FirstName": "Test1",
"LastName": "Test2",
"Address": "London, GB",
"Error": "Something's gone wrong"
},
{
"FirstName": "Test3",
"LastName": "Test4",
"Address": "NewYork, US",
"Error": "Something's gone wrong"
},
{
"DisplayName": "ContactNumber",
"Value": "01234 123 123"
}
]
I want to build a JSON Object like this in C#
[
"pages":{
"FirstName": "Test1",
"LastName": "Test2",
"Address": "London, GB",
"Error": "Something's gone wrong"
},
{
"FirstName": "Test3",
"LastName": "Test4",
"Address": "NewYork, US",
"Error": "Something's gone wrong"
},
"labels": {
"DisplayName": "ContactNumber",
"Value": "01234 123 123"
}
}
]
I've created a Model with above output properties but they are not getting mapped when I deserialize the object into that Model. All values are returning null.
var deserializedData = JsonConvert.DeserializeObject<List<Config>>(serializedData);
the response I receive when I check is
[
{
"pages": null,
"labels": null
},
{
"pages": null,
"labels": null
}
]
Can anyone help me build the Custom Model for this format I want in C#.
Thanks in advance.
What you have is a polymorphic JSON array containing a variety of types of objects, distinguishable by the presence of specific properties ("DisplayName" vs "FirstName", e.g.). What you would like to do is to deserialize that into a c# model in which each possible array item gets added to a collection-valued property of your model, where the collection property is chosen to have the correct item type.
This can be accomplished by using a custom JsonConverter. Since the problem statement is generic I'm going to make the converter be generic. A hardcoded converter would require less code.
First, define your desired model as follows:
public class Page
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Error { get; set; }
}
public class Label
{
public string DisplayName { get; set; }
public string Value { get; set; }
}
public class RootObject
{
public List<Page> pages { get; set; }
public List<Label> labels { get; set; }
}
Next define the following converter:
public class PolymorphicArrayToObjectConverter<TObject> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(TObject).IsAssignableFrom(objectType);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
static JsonObjectContract FindContract(JObject obj, IEnumerable<Type> derivedTypes, JsonSerializer serializer)
{
List<JsonObjectContract> bestContracts = new List<JsonObjectContract>();
foreach (var type in derivedTypes)
{
if (type.IsAbstract)
continue;
var contract = serializer.ContractResolver.ResolveContract(type) as JsonObjectContract;
if (contract == null)
continue;
if (obj.Properties().Select(p => p.Name).Any(n => contract.Properties.GetClosestMatchProperty(n) == null))
continue;
if (bestContracts.Count == 0 || bestContracts[0].Properties.Count > contract.Properties.Count)
{
bestContracts.Clear();
bestContracts.Add(contract);
}
else if (contract.Properties.Count == bestContracts[0].Properties.Count)
{
bestContracts.Add(contract);
}
}
return bestContracts.Single();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType != JsonToken.StartArray)
throw new InvalidOperationException("JSON token is not an array at path: " + reader.Path);
var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType);
existingValue = existingValue ?? contract.DefaultCreator();
var lookup = contract
.Properties
.Select(p => new { Property = p, PropertyContract = serializer.ContractResolver.ResolveContract(p.PropertyType) as JsonArrayContract })
.Where(i => i.PropertyContract != null)
.ToDictionary(i => i.PropertyContract.CollectionItemType);
var types = lookup.Select(i => i.Key).ToList();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
case JsonToken.EndArray:
return existingValue;
default:
{
var itemObj = JObject.Load(reader);
var itemContract = FindContract(itemObj, types, serializer);
if (itemContract == null)
continue;
var item = serializer.Deserialize(itemObj.CreateReader(), itemContract.UnderlyingType);
var propertyData = lookup[itemContract.UnderlyingType];
var collection = propertyData.Property.ValueProvider.GetValue(existingValue);
if (collection == null)
{
collection = propertyData.PropertyContract.DefaultCreator();
propertyData.Property.ValueProvider.SetValue(existingValue, collection);
}
collection.GetType().GetMethod("Add").Invoke(collection, new [] { item });
}
break;
}
}
// Should not come here.
throw new JsonSerializationException("Unclosed array at path: " + reader.Path);
}
}
Then, deserialize and re-serialize your RootObject collection as follows:
var settings = new JsonSerializerSettings
{
Converters = { new PolymorphicArrayToObjectConverter<RootObject>() },
};
var root = new List<RootObject> { JsonConvert.DeserializeObject<RootObject>(jsonString, settings) };
var outputJson = JsonConvert.SerializeObject(root, Formatting.Indented);
As a result, the following JSON will be generated:
[
{
"pages": [
{
"FirstName": "Test1",
"LastName": "Test2",
"Address": "London, GB",
"Error": "Something's gone wrong"
},
{
"FirstName": "Test3",
"LastName": "Test4",
"Address": "NewYork, US",
"Error": "Something's gone wrong"
}
],
"labels": [
{
"DisplayName": "ContactNumber",
"Value": "01234 123 123"
}
]
}
]
Sample fiddle.
Note - code to automatically infer the array item type was adapted from this answer.
you json is not valid json structure for parsing , this not valid at all(check what is wrong with it here : https://jsonlint.com/)
not valid json string given by you
[
"pages":{
"FirstName": "Test1",
"LastName": "Test2",
"Address": "London, GB",
"Error": "Something's gone wrong"
},
{
"FirstName": "Test3",
"LastName": "Test4",
"Address": "NewYork, US",
"Error": "Something's gone wrong"
},
"labels": {
"DisplayName": "ContactNumber",
"Value": "01234 123 123"
}
}
]
However I fixed json you given
Fixed and working json
[{
"pages": [{
"FirstName": "Test1",
"LastName": "Test2",
"Address": "London, GB",
"Error": "Something's gone wrong"
},
{
"FirstName": "Test3",
"LastName": "Test4",
"Address": "NewYork, US",
"Error": "Something's gone wrong"
}
],
"labels": {
"DisplayName": "ContactNumber",
"Value": "01234 123 123"
}
}]
After applying fix json , your C# object is
public class Page
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Error { get; set; }
}
public class Labels
{
public string DisplayName { get; set; }
public string Value { get; set; }
}
public class RootObject
{
public List<Page> pages { get; set; }
public Labels labels { get; set; }
}
and I tried this with my fixed json and its working fine.
End of Edit
Below code is working fine for me with the class structure i provided you in below
for list
var jsonString = "[{ \"pages\": {\"id\": 12345, \"name\": \"John Doe\", \"number\": \"123\", \"test\": "+
"\"John\" }, \"labels\": { \"test\": \"test1\", \"test2\": \"test2\" } }," +
"{ \"pages\": {\"id\": 12345, \"name\": \"John Doe\", \"number\": \"123\", \"test\": "+
"\"John\" }, \"labels\": { \"test\": \"test1\", \"test2\": \"test2\" } }]";
var deserializedData = JsonConvert.DeserializeObject<List<RootObject>>(jsonString);
With single object as input
var jsonString = "{ \"pages\": {\"id\": 12345, \"name\": \"John Doe\", \"number\": \"123\", \"test\": "+
"\"John\" }, \"labels\": { \"test\": \"test1\", \"test2\": \"test2\" } }";
var deserializedData = JsonConvert.DeserializeObject<RootObject>(jsonString);
based on input
{ "pages": { "id": 12345, "name": "John Doe", "number": "123", "test":
"John" }, "labels": { "test": "test1", "test2": "test2" } }
below is generated classes
public class Pages
{
public int id { get; set; }
public string name { get; set; }
public string number { get; set; }
public string test { get; set; }
}
public class Labels
{
public string test { get; set; }
public string test2 { get; set; }
}
public class RootObject
{
public Pages pages { get; set; }
public Labels labels { get; set; }
}
If you have Json with you than you can generate C# class using visual studio itself.
In visual studio Find "Paste Sepcial" menu. i.e. copy you json string and click on Paste special , it will generate C# class for you.
you can follow my post : Generate Class From JSON or XML in Visual Studio
or use online website like : json2csharp

Disabling null type in Newtonsoft JSON.NET schema

I have an MVC application, that serializes my model into json schema (using Newtonsoft json.net schema). The problem is that items in my array have type ["string", "null"], but what I need is just "string". Here is code for my class:
public class Form
{
[Required()]
public string[] someStrings { get; set; }
}
This is schema made by Json.net schema:
"someStrings": {
"type": "array",
"items": {
"type": [
"string",
"null"
]
}
}
While I am expecting this:
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
Help me get rid of that "null" please.
Try setting DefaultRequired to DisallowNull when you generate the schema:
JSchemaGenerator generator = new JSchemaGenerator()
{
DefaultRequired = Required.DisallowNull
};
JSchema schema = generator.Generate(typeof(Form));
schema.ToString();
Output:
{
"type": "object",
"properties": {
"someStrings": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
You can try this:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
Try this ::
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public decimal? Salary { get; set; }
}
Employee employee= new Employee
{
Name = "Heisenberg",
Age = 44
};
string jsonWithNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);
output: with null
// {
// "Name": "Heisenberg",
// "Age": 44,
// "Salary": null
// }
string jsonWithOutNullValues = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
output: without null
// {
// "Name": "Heisenberg",
// "Age": 44
// }

Categories