Converting C++ Class to JSON

How do I turn a C# object into a JSON string in .NET?

Please Note

Microsoft recommends that you DO NOT USE JavaScriptSerializer

See the header of the documentation page:

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.



Original answer:

You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):

using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);

A full example:

using System;
using System.Web.Script.Serialization;

public class MyDate
{
public int year;
public int month;
public int day;
}

public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}

class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}

Converting C++ class to JSON

JSON Spirit would allow you to do it like so:

Object addr_obj;

addr_obj.push_back( Pair( "house_number", 42 ) );
addr_obj.push_back( Pair( "road", "East Street" ) );
addr_obj.push_back( Pair( "town", "Newtown" ) );

ofstream os( "address.txt" );
os.write( addr_obj, os, pretty_print );
os.close();

Output:

{
"house_number" : 42,
"road" : "East Street",
"town" : "Newtown"
}

The json_map_demo.cpp would be a nice place to start, I suppose.

Converting C# Objects to Json format

You didn't write which version of asp .net core you use.

In version 2.0 Json Newtonsoft library is used to handle json serialization/deserialization.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }

In version 3.0 has been introduced new default library for handling json operations System.Text.Json, but you can change configuration to still use Newtonsoft. Example usage of the System.Text.Json.

string jsonString;
jsonString = JsonSerializer.Serialize(weatherForecast);
// {
// "Date": "2019-08-01T00:00:00-07:00",
// "TemperatureCelsius": 25,
// "Summary": "Hot",
// "DatesAvailable": ["2019-08-01T00:00:00-07:00",
// "2019-08-02T00:00:00-07:00"],
// "TemperatureRanges": {
// "Cold": {
// "High": 20,
// "Low": -10
// },
// "Hot": {
// "High": 60,
// "Low": 20
// }
// },
// "SummaryWords": ["Cool",
// "Windy",
// "Humid"]
// }

Convert C# Object to Json Object

To create correct JSON first you need to prepare appropriate model. It can be something like that:

[DataContract]
public class Customer
{
[DataMember(Name = "gors_descr")]
public string ProductDescription { get; set; }

[DataMember(Name = "b_name_first")]
public string Fname { get; set; }

[DataMember(Name = "b_name_last")]
public string Lname { get; set; }
}

To be able to use Data attributes you will need to choose some other JSON serializer. For example DataContractJsonSerializer or Json.NET(I will use it in this example).

Customer customer = new Customer
{
ProductDescription = tbDescription.Text,
Fname = tbFName.Text,
Lname = tbLName.Text
};

string creditApplicationJson = JsonConvert.SerializeObject(
new
{
jsonCreditApplication = customer
});

So jsonCreditApplication variable will be:

{
"jsonCreditApplication": {
"gors_descr": "Appliances",
"b_name_first": "Marisol",
"b_name_last": "Testcase"
}
}

How to convert C# class object to json?

I believe you are new to this and want a working sample to kick off the work.

Here you go.

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Program
{
public static void Main()
{
var o = new UserResponse();
o.Age = "25";
o.Gender = "Male";
o.Message = "Hello";
o.UserInfo = new User();
o.UserInfo.Id = 1;
o.UserInfo.FirstName = "John";
o.UserInfo.LastName = "Doe";
o.UserInfo.Balance = 1000M;
var json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()} );
Console.WriteLine(json);
}
}

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public decimal Balance { get; set; }
}

public class UserResponse
{
public User UserInfo { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Message { get; set; }
}

Try it out here...

Sample Code

Convert C# class to Json with customized structure

As you have tagged your question with json.net, you can do this by applying a custom JsonConverter to the "selected attributes" that should be nested inside a {"value" : ... } object when serialized.

First, define the following converter:

public class NestedValueConverter<T> : JsonConverter
{
class Value
{
public T value { get; set; }
}

public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.MoveToContent().TokenType)
{
case JsonToken.Null:
return null;

default:
return serializer.Deserialize<Value>(reader).value;
}
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, new Value { value = (T)value });
}
}

public static partial class JsonExtensions
{
public static JsonReader MoveToContent(this JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
reader.Read();
while (reader.TokenType == JsonToken.Comment && reader.Read())
;
return reader;
}
}

Now, apply it the "selected attributes" of PrimaryContact as follows:

public class PrimaryContact
{
[JsonConverter(typeof(NestedValueConverter<string>))]
public string PrefixTitle { get; set; }

public string SurName { get; set; }

public string GivenName { get; set; }
}

And you will be able to deserialize and serialize as follows:

var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
};
var root = JsonConvert.DeserializeObject<RootObject>(jsonString, settings);

var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);

Notes:

  • As the converter is intended to be applied directly using the attributes [JsonConverter(typeof(NestedValueConverter<...>))] or [JsonProperty(ItemConverterType = typeof(NestedValueConverter<...>))], CanConvert, which is only called when the converter is included in settings, is not implemented.

  • The converter is generic in case you need to nest non-string values.

Sample fiddle here.



Related Topics



Leave a reply



Submit