I have serialized my mvc form and now wants to deserialize it in c#.Please help me to tackle this issue.Following is my code of frontend
<input type="search" id="txtsearch">
<input type="button" id="btnsearch" />
<script type="text/javascript">
$(function () {
DrawTable(0);
$('#btnsearch').click(function (e) {
var searchname = $('#txtsearch').val();
var form = $('form').serialize();
//var form = $(this).serializeArray();
DrawTable(form);
});
</script>
and following is the method where i want to get values from serialized data by deserializing
public JsonResult GetAllCustomers(string sEcho, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0, string filters, int UserId = 0,string form="") {
string sortDirection = sSortDir_0;
DataTableGridModel resultModel = new Logic(x,y ).GetCustomersForGrid(sEcho, sColumns, iDisplayStart, iDisplayLength, sSearch, iSortCol_0, sSortDir_0, UserId);
return Json(resultModel, JsonRequestBehavior.AllowGet);
}
Use Newtonsoft.Json.dll for serialization and deserialization of json data in C#
Create below methods using Newtonsoft.Json.dll and invoke deserialize method by passing json data in string format.
private static JsonSerializerSettings CreateSettings()
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
return settings;
}
private static Newtonsoft.Json.JsonSerializer CreateSerializer()
{
var settings = CreateSettings();
return Newtonsoft.Json.JsonSerializer.Create(settings);
}
public T Deserialize<T>(object target)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
var result = default(T);
var json = target as string;
if (json != null)
{
var serializer = CreateSerializer();
using (var stringReader = new StringReader(json))
{
using (JsonReader jsonReader = new JsonTextReader(stringReader))
{
result = serializer.Deserialize<T>(jsonReader);
}
}
}
return result;
}
1).ENCODE FORM AS JSON STRING ON CLIENT
//in javascript, serialize the form to JSON:
// -- this will only work if all elements on the form have a name attribute -
var stringToReturnToServer = JSON.stringify($('form').serializeArray());
2). DECODE JSON STRING TO DICTIONARY, SO YOU CAN RETRIEVE ELEMENT BY NAME
Server-side, you'll be dealing with a string containing JSON array of objects that each have two properties, name and value. This translates nicely to a C# Dictionary<string,string>
using Newtonsoft.Json;
private class FormField
{
[JsonProperty("name")]
public string a { get; set; }
[JsonProperty("value")]
public string b { get; set; }
}
private void ReadFormData(string sFormData)
{
//this will throw if you give two form fields the same name in your HTML.
Dictionary<string,string> asFormData = JsonConvert.DeserializeObject<List<FormField>>(sFormData).ToDictionary(x => x.a, x => x.b);
//VALUES OF FORM ELEMENTS NOW ACCESSIBLE BY NAME IN DICTIONARY
string sSearchText = asFormData["txtsearch"];
}
...the code here is limited to serialzing and deserializing, you'll need to GET or POST the actual JSON string back to the server.
Related
I am looking for the equivalent of Golang's json: "inline" tag with C#'s System.Text.Json.
For example, I have the following class structure in C#:
class Outer{
public string Hello;
public Inner TheInner;
}
class Inner{
public string Earth;
public string Moon;
}
And I want the serialized and deserialized JSON text to be
{
"Hello" : "example_value_01",
"Earth" : "example_value_02",
"Moon" : "example_value_03"
}
In Golang, I can achieve this with the following structure definition
type Outer struct{
Hello string
TheInner Inner `json: "inline"`
}
type Inner struct{
Earth string
Moon string
}
However, I cannot find a decent way to do this in C#'s System.Text.Json.
To reach it in c# , you don't need any custom classes at all,you can use a dictionary
var dict = new Dictionary<string, string> {
{"Hello","example1"},
{"World","example2"}
};
var json= System.Text.Json.JsonSerializer.Serialize(dict,new JsonSerializerOptions { WriteIndented = true});
result
{
"Hello": "example1",
"World": "example2"
}
but if you want it a hard way it is much easier to make it using Newtonsoft.Json since Text.Json needs a custom serializer for almost everything
using Newtonsoft.Json;
var json = SerializeOuterObj(obj, "TheInner");
obj = DeserializeOuterObj(json);
public string SerializeOuterObj(object outerObj, string innerObjectPropertyName)
{
var jsonParsed = JObject.FromObject(outerObj);
var prop = jsonParsed.Properties().Where(i => i.Name == innerObjectPropertyName).First();
prop.Remove();
foreach (var p in ((JObject)prop.Value).Properties())
jsonParsed.Add(p.Name, p.Value);
return jsonParsed.ToString();
}
public Outer DeserializeOuterObj(string json)
{
var jsonParsed = JObject.Parse(json);
var outer = jsonParsed.ToObject<Outer>();
outer.TheInner = jsonParsed.ToObject<Inner>();
return outer;
}
This solution uses reflexion, so is independant of number of string items in the class Inner and independant too of name of Inner Class, just you have to respect if its property or field:
public class Outer
{
public string? Hello;
public Inner? TheInner { get; set; }
}
public class Inner
{
public string? World1;
public string? World2;
public string? World3;
}
the program using the nested class:
var json= "{\"Hello\": \"hello\",\"World1\":\"world1\", \"World2\": \"world2\", \"World3\": \"world3\"}";
var ou = deserialize(json);
json = serialize(ou);
the methods serialize and deserialize:
public Outer deserialize(string json)
{
var fieldhello = typeof(Outer).GetFields().First();
var propinner = typeof(Outer).GetProperties().First();
var subfieldsinner = typeof(Inner).GetFields().ToArray();
var document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;
var outer = new Outer();
var inner = new Inner();
var innerstArr = subfieldsinner.Select(f => (field: f, value: root.TryGetProperty(f.Name, out var item) ? item.GetString() : null));
foreach(var p in innerstArr)
p.field.SetValue(inner, p.value);
string? hellost = root.TryGetProperty(fieldhello.Name, out var item) ? item.GetString() : null;
fieldhello.SetValue(outer, hellost);
propinner.SetValue(outer, inner);
return outer;
}
public string serialize(Outer outer)
{
var fieldhello = outer.GetType().GetFields().First();
var propinner = outer.GetType().GetProperties().First();
var inn = (Inner) propinner.GetValue(outer, null);
var subfieldsinner = inn.GetType().GetFields().ToArray();
using var ms = new MemoryStream();
using var writer = new Utf8JsonWriter(ms);
writer.WriteStartObject();
writer.WriteString(fieldhello.Name, (string?)fieldhello.GetValue(outer));
foreach(var f in subfieldsinner)
writer.WriteString(f.Name, (string?)f.GetValue(inn));
writer.WriteEndObject();
writer.Flush();
string json = Encoding.UTF8.GetString(ms.ToArray());
return json;
}
I am trying to parse the result from the google speech to text API. The json response is :
{"result":[]}
{"result":[
{"alternative":[
{"transcript":"hello Google how are you feeling","confidence":0.96274596},
{"transcript":"hello Google how are you today","confidence":0.97388196},
{"transcript":"hello Google how are you picking","confidence":0.97388196},
{"transcript":"hello Google how are you kidding","confidence":0.97388196}
]
,"final":true}]
,"result_index":0
}
Now i am trying to parse it through JObject. The problem is occurring in parsing the Result object which is appearing twice so, how do i parse the second Result object. Here is my code which i am trying is :
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ReadToEnd()+SR_Response.ToString());
String json_response = SR_Response.ReadToEnd() + SR_Response.ToString();
JObject joo = JObject.Parse(json_response);
JArray ja = (JArray)joo["result"];
foreach (JObject o in ja)
{
JArray ja2 = (JArray)o["alternative"];
foreach (JObject h in ja2)
{
Console.WriteLine(h["transcript"]);
}
}
Next solution i tried using deserialize object code is:
string responseFromServer = (SR_Response.ReadToEnd());
String[] jsons = responseFromServer.Split('\n');
String text = "";
foreach (String j in jsons)
{
dynamic jsonObject = JsonConvert.DeserializeObject(j);
if (jsonObject == null || jsonObject.result.Count <= 0)
{
continue;
}
Console.WriteLine((string)jsonObject["result"]["alternative"][0]["transcript"]);
text = jsonObject.result[0].alternative[0].transcript;
}
Console.WriteLine("MESSAGE : "+text);
What you have is a series of JSON root objects concatenated together into a single stream. As explained in Read Multiple Fragments With JsonReader such a stream can be deserialized by setting JsonReader.SupportMultipleContent = true. Thus, to deserialize your stream, you should first introduce the following extension methods:
public static class JsonExtensions
{
public static IEnumerable<T> DeserializeObjects<T>(Stream stream, JsonSerializerSettings settings = null)
{
var reader = new StreamReader(stream); // Caller should dispose
return DeserializeObjects<T>(reader, settings);
}
public static IEnumerable<T> DeserializeObjects<T>(TextReader textReader, JsonSerializerSettings settings = null)
{
var ser = JsonSerializer.CreateDefault(settings);
var reader = new JsonTextReader(textReader); // Caller should dispose
reader.SupportMultipleContent = true;
while (reader.Read())
{
if (reader.TokenType == JsonToken.None || reader.TokenType == JsonToken.Undefined || reader.TokenType == JsonToken.Comment)
continue;
yield return ser.Deserialize<T>(reader);
}
}
}
Next, using a code-generation utility such as http://json2csharp.com/, generate c# classes for a single JSON root object, like so:
public class Alternative
{
public string transcript { get; set; }
public double confidence { get; set; }
}
public class Result
{
public List<Alternative> alternative { get; set; }
public bool final { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public int result_index { get; set; }
}
And deserialize as follows:
List<RootObject> results;
using (var stream = HWR_Response.GetResonseStream())
{
results = JsonExtensions.DeserializeObjects<RootObject>(stream).ToList();
}
Having done this you can use standard c# programming techniques such as Linq to enumerate the transcript values, such as:
var transcripts = results
.SelectMany(r => r.result)
.SelectMany(r => r.alternative)
.Select(a => a.transcript)
.ToList();
If you don't want define a fixed data model for your JSON collection, you can deserialize directly to a list of JObject like so:
List<JObject> objs;
using (var stream = HWR_Response.GetResonseStream())
{
objs = JsonExtensions.DeserializeObjects<JObject>(stream).ToList();
}
Then you can use SelectTokens() to select the values of all the "transcript" properties nested inside each object:
var transcripts = objs
// The following uses the JSONPath recursive descent operator ".." to pick out all properties named "transcript".
.SelectMany(o => o.SelectTokens("..transcript"))
.Select(t => t.ToString())
.ToList();
Updated sample fiddle showing both options.
I got a Windows Phone 8.1 app.
I am trying to parse a list of objects returned by my Web API call.
On my server I have this code:
Default.aspx:
[WebMethod]
public static List<Shared.PremisesResponse> GetPremises(string emailaddress)
{
Premises premises = new Premises();
return premises.GetPremises(emailaddress);
}
In that premise object class
public List<Shared.PremisesResponse> GetPremises(string emailAlias)
{
DAL dal = new DAL();
List<Shared.PremisesResponse> premises = new List<Shared.PremisesResponse>();
try
{
DataSet dtMacs = dal.GetMacs(emailAlias);
for (int index = 0; index < dtMacs.Tables[0].Rows.Count; index++)
{
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = dtMacs.Tables[0].Rows[index]["PremiseName"].ToString().Trim();
itemMAC1.Alias = dtMacs.Tables[0].Rows[index]["Alias"].ToString().Trim();
premises.Add(itemMAC1);
}
}
catch (Exception ex)
{
Email2.SendError("Premises.GetPremises:" + ex.ToString(), emailAlias);
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = "ERROR";
itemMAC1.Alias = ex.ToString();
premises.Add(itemMAC1);
}
return premises;
}
The class Shared.Premise:
public class PremisesResponse
{
public string PremiseName;
public string Alias;
}
In my WP8.1 client app:
public async static Task<List<D2>> GetPremises( string emailaddress)
{
List<D2> premises = new List<D2>();
try
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/NativeApp/Default.aspx/GetPremises",
new { emailaddress = emailaddress });
var str = await resp.Content.ReadAsStringAsync();
var premisesResponse = JsonConvert.DeserializeObject<List<D2>>(str);
foreach (var pr in premisesResponse)
{
D2 d2 = new D2();
d2.Alias = pr.Alias;
d2.PremiseName = pr.PremiseName;
premises.Add(d2);
}
}
}
catch (Exception ex)
{
//evMessage(Enums.MessageType.Error, serverRegister);
}
return premises;
}
And the objects I am using in my client:
public class D2
{
public string __type { get; set; }
public string PremiseName;
public string Alias;
}
public class PremisesResponse
{
public D2 d { get; set; }
}
'var str' returns this value:
{"d":[{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"Informatica 2000","Alias":"9A5C3-E1945-3D315-BB43C"},{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"My Office","Alias":"40387-69918-FC22F-C444B"}]}
The error occurs on this line:
var premisesResponse = JsonConvert.DeserializeObject<List<PremisesResponse>>(str);
The error message is:
[Informed.D2]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'd', line 1, position 5.
I have no problems returning a single value, just with returning a list of this object.
Any pointers would be helpful.
Thanks
You're trying to deserialize a List<D2> rather than a single D2 object:
public class PremisesResponse
{
public D2[] d { get; set; }
}
And then simply:
PremisesResponse response = JsonConvert.DeserializeObject<PremisesResponse>(str);
I'm trying to deserialize a Facebook friend's Graph API call into a list of objects. The JSON object looks like:
{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
It's not working, because the primitive object is invalid. How can I deserialize this?
You need to create a structure like this:
public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
Then you should be able to do:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
The names of my classes are just an example. You should use proper names.
Adding a sample test:
string json =
#"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
Produces:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
Sometimes I prefer dynamic objects:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}
A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:
http://json2csharp.com/
It will provide you with a starting point to touch up your classes for deserialization.
Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();
Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
I agree with Icarus (would have commented if I could),
but instead of using a CustomObject class,
I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Serialization:
// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);
Response.Write(jsonData);
Deserialization::
To deserialize a dynamic object
string json = #"{
'Name': 'name',
'Description': 'des'
}";
var res = JsonConvert.DeserializeObject< dynamic>(json);
Response.Write(res.Name);
If you're using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.
The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.
Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu Edit → Paste Special → Paste JSON as classes).
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Response
{
public List<Person> Data { get; set; }
}
Then you can deserialize using:
var people = JsonSerializer.Deserialize<Response>(json);
If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:
var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);
You can use this extensions
public static class JsonExtensions
{
public static T ToObject<T>(this string jsonText)
{
return JsonConvert.DeserializeObject<T>(jsonText);
}
public static string ToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
Here is another site that will help you with all the code you need as long as you have a correctly formated JSON string available:
https://app.quicktype.io/
I want to be able to convert a List<T> into a specific JSON table-like format. In my case, the T will always be a simple object (no nested properties). Here are two examples to illustrate what I want.
Example #1: List<Person> to JSON
// C# list of Persons
var list = new List<Person>() {
new Person() { First = "Jesse", Last = "Gavin", Twitter = "jessegavin" },
new Person() { First = "John", Last = "Sheehan", Twitter = "johnsheehan" }
};
// I want to transform the list above into a JSON object like so
{
columns : ["First", "Last", "Twitter"],
rows: [
["Jesse", "Gavin", "jessegavin"],
["John", "Sheehan", "johnsheehan"]
]
}
Example #2: List<Address> to JSON
// C# list of Locations
var list = new List<Location>() {
new Location() { City = "Los Angeles", State = "CA", Zip = "90210" },
new Location() { City = "Saint Paul", State = "MN", Zip = "55101" },
};
// I want to transform the list above into a JSON object like so
{
columns : ["City", "State", "Zip"],
rows: [
["Los Angeles", "CA", "90210"],
["Saint Paul", "MN", "55101"]
]
}
Is there a way to tell JSON.net to serialize an object in this manner? If not, how could I accomplish this? Thanks.
UPDATE:
Thanks to #Hightechrider's answer, I was able to write some code that solves the problem.
You can view a working example here https://gist.github.com/1153155
Using reflection you can get a list of properties for the type:
var props = typeof(Person).GetProperties();
Given an instance of a Person p you can get an enumeration of the property values thus:
props.Select(prop => prop.GetValue(p, null))
Wrap those up in a generic method, add your favorite Json serialization and you have the format you want.
Assuming your using .Net 4 this should do everything you want. The class actually lets you convert to either XML or JSON. The Enum for CommunicationType is at the bottom. The serializer works best if the class your passing it has been decorated with DataContract & DataMember attributes. I've included a sample at the bottom. It will also take an anonymous type so long as it's all simple types.
Reflection would work as well but then you have to understand all the JSON nuances to output complex data types, etc. This used the built-in JSON serializer in .Net 4. One more note, because JSON does not define a date type .Net puts dates in a funky ASP.Net custom format. So long as your deserializing using the built-in deserializer it works just fine. I can dig up the documentation on that if you need.
using System;
using System.Xml.Serialization;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml.Linq;
internal class Converter
{
public static string Convert<T>(T obj, CommunicationType format, bool indent = false, bool includetype = false)
{
if (format == CommunicationType.XML)
{
return ToXML<T>(obj, includetype, indent);
}
else if (format == CommunicationType.JSON)
{
return ToJSON<T>(obj);
}
else
{
return string.Empty;
}
}
private static string ToXML<T>(T obj, bool includetype, bool indent = false)
{
if (includetype)
{
XElement xml = XMLConverter.ToXml(obj, null, includetype);
if(indent) {
return xml.ToString();
}
else
{
return xml.ToString(SaveOptions.DisableFormatting);
}
}
else
{
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
XmlSerializer xs = new XmlSerializer(typeof(T));
StringBuilder sbuilder = new StringBuilder();
var xmlws = new System.Xml.XmlWriterSettings() { OmitXmlDeclaration = true, Indent = indent };
ns.Add(string.Empty, string.Empty);
using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
{
xs.Serialize(writer, obj, ns);
}
string result = sbuilder.ToString();
ns = null;
xs = null;
sbuilder = null;
xmlws = null;
return result;
}
}
private static string ToJSON<T>(T obj)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
string result = string.Empty;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
ser.WriteObject(ms, obj);
result = encoding.GetString(ms.ToArray());
ms.Close();
encoding = null;
ser = null;
return result;
}
}
}
[DataContract()]
public enum CommunicationType : int
{
[XmlEnum("0"), EnumMember(Value = "0")]
XML = 0,
[XmlEnum("1"), EnumMember(Value = "1")]
JSON = 1
}
[DataContract(Namespace = "")]
public partial class AppData
{
[DataMember(Name = "ID")]
public string ID { get; set; }
[DataMember(Name = "Key")]
public string Key { get; set; }
[DataMember(Name = "Value")]
public string Value { get; set; }
[DataMember(Name = "ObjectType")]
public string ObjectType { get; set; }
}
Any specific reason why you don't need the standard format?
To actually answer the question:
Since this is something that is outside of JSON syntax I can't think of a way to implement this within the default framework.
One solution would be to leverage attributes decorate the properties you want transported over the wired with a custom attribute and using Reflection cycle through the properties and output their property names as the column headers and then cycle throw the objects and write the values. Generic enough so it could be applied across other objects as well.
public class Location
{
[JsonFooAttribute("City")]
public string city {get;set;}
[JsonFooAttribute("State")]
public string state {get;set;}
}