Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 901 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I turn a C# object into a JSON string in .NET?

#1
I have classes like these:

class MyDate
{
int year, month, day;
}

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

And I would like to turn a `Lad` object into a **JSON** string like this:

{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}

(Without the formatting). I found [this link][1], but it uses a namespace that's not in **.NET 4**. I also heard about [JSON.NET][2], but their site seems to be down at the moment, and I'm not keen on using external DLL files.

Are there other options besides manually creating a **JSON** string writer?

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#2
Wooou! Really better using a JSON framework :)

Here is my example using Json.NET (

[To see links please register here]

):


using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace com.blogspot.jeanjmichel.jsontest.model
{
public class Contact
{
private Int64 id;
private String name;
List<Address> addresses;

public Int64 Id
{
set { this.id = value; }
get { return this.id; }
}

public String Name
{
set { this.name = value; }
get { return this.name; }
}

public List<Address> Addresses
{
set { this.addresses = value; }
get { return this.addresses; }
}

public String ToJSONRepresentation()
{
StringBuilder sb = new StringBuilder();
JsonWriter jw = new JsonTextWriter(new StringWriter(sb));

jw.Formatting = Formatting.Indented;
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(this.Id);
jw.WritePropertyName("name");
jw.WriteValue(this.Name);

jw.WritePropertyName("addresses");
jw.WriteStartArray();

int i;
i = 0;

for (i = 0; i < addresses.Count; i++)
{
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(addresses[i].Id);
jw.WritePropertyName("streetAddress");
jw.WriteValue(addresses[i].StreetAddress);
jw.WritePropertyName("complement");
jw.WriteValue(addresses[i].Complement);
jw.WritePropertyName("city");
jw.WriteValue(addresses[i].City);
jw.WritePropertyName("province");
jw.WriteValue(addresses[i].Province);
jw.WritePropertyName("country");
jw.WriteValue(addresses[i].Country);
jw.WritePropertyName("postalCode");
jw.WriteValue(addresses[i].PostalCode);
jw.WriteEndObject();
}

jw.WriteEndArray();

jw.WriteEndObject();

return sb.ToString();
}

public Contact()
{
}

public Contact(Int64 id, String personName, List<Address> addresses)
{
this.id = id;
this.name = personName;
this.addresses = addresses;
}

public Contact(String JSONRepresentation)
{
//To do
}
}
}

The test:

using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;

namespace com.blogspot.jeanjmichel.jsontest.main
{
public class Program
{
static void Main(string[] args)
{
List<Address> addresses = new List<Address>();
addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));

Contact contact = new Contact(1, "Ayrton Senna", addresses);

Console.WriteLine(contact.ToJSONRepresentation());
Console.ReadKey();
}
}
}

The result:

{
"id": 1,
"name": "Ayrton Senna",
"addresses": [
{
"id": 1,
"streetAddress": "Rua Dr. Fernandes Coelho, 85",
"complement": "15º andar",
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": "05423040"
},
{
"id": 2,
"streetAddress": "Avenida Senador Teotônio Vilela, 241",
"complement": null,
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": null
}
]
}

Now I will implement the constructor method that will receives a JSON string and populates the class' fields.
Reply

#3
**Serializer**

public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
});
using (var writer = new StreamWriter(filePath, append))
{
writer.Write(contentsToWriteToFile);
}
}

**Object**

namespace MyConfig
{
public class AppConfigurationSettings
{
public AppConfigurationSettings()
{
/* initialize the object if you want to output a new document
* for use as a template or default settings possibly when
* an app is started.
*/
if (AppSettings == null) { AppSettings=new AppSettings();}
}

public AppSettings AppSettings { get; set; }
}

public class AppSettings
{
public bool DebugMode { get; set; } = false;
}
}

**Implementation**

var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);

**Output**

{
"AppSettings": {
"DebugMode": false
}
}
Reply

#4
Use the `DataContractJsonSerializer` class: [MSDN1](

[To see links please register here]

), [MSDN2](

[To see links please register here]

).

My example: [HERE](

[To see links please register here]

).

It can also safely deserialize objects from a JSON string, unlike `JavaScriptSerializer`. But personally I still prefer [Json.NET](

[To see links please register here]

).
Reply

#5
If you are in an ASP.NET MVC web controller it's as simple as:

string ladAsJson = Json(Lad);

Can't believe no one has mentioned this.
Reply

#6
Use [Json.Net][1] library, you can download it from Nuget Packet Manager.


[1]:

[To see links please register here]



**Serializing to Json String:**

var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

**Deserializing to Object:**

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through