Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to JSON string in C# [duplicate]

Tags:

json

c#

Possible Duplicate:
Turn C# object into a JSON string in .NET 4

In the Java, I have a code to convert java object to JSON string. How to do the similar in the C# ? which JSON library I should use ?

Thanks.

JAVA code

import net.sf.json.JSONArray; import net.sf.json.JSONObject;  public class ReturnData {     int total;      List<ExceptionReport> exceptionReportList;        public String getJSon(){         JSONObject json = new JSONObject();           json.put("totalCount", total);          JSONArray jsonArray = new JSONArray();         for(ExceptionReport report : exceptionReportList){             JSONObject jsonTmp = new JSONObject();             jsonTmp.put("reportId", report.getReportId());                   jsonTmp.put("message", report.getMessage());                         jsonArray.add(jsonTmp);                  }          json.put("reports", jsonArray);         return json.toString();     }     ... } 
like image 605
user595234 Avatar asked Jul 05 '12 13:07

user595234


People also ask

Can we convert string to JSON in C?

Using JsonConverter JsonConvert class has a method to convert to and from JSON string, SerializeObject() and DeserializeObject() respectively. It can be used where we won't to convert to and from a JSON string.

How do I convert a dictionary to a JSON string in C #?

We do this, because both the Key and Value has to be of type string, as a requirement for serialization of a Dictionary . var json = new JavaScriptSerializer(). Serialize(convertedDictionary); //You can then serialize the Dictionary, as both the Key and Value is of type string, which is required for serialization.

What is JsonProperty C#?

This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }


1 Answers

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData  {     public int totalCount { get; set; }     public List<ExceptionReport> reports { get; set; }   }  public class ExceptionReport {     public int reportId { get; set; }     public string message { get; set; }   }   string json = JsonConvert.SerializeObject(myReturnData); 
like image 94
foson Avatar answered Oct 04 '22 15:10

foson