Parsing multiple objects using Jobject in Newtonsoft.Json.Linq - c#

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.

Related

How to inline JSON structure with System.Text.Json

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;
}

Deserialize property with a different name?

I have an interface with exposes a property called Pages:
public interface INameSet
{
IQueryable<string> Names { get; }
}
I have this class which implements the interface and must also be parsed from a JSON object:
[DataContract(Name = "surveyPageSet")]
public class SurveyPage : INameSet
{
[DataMember(Name = "names")]
public List<string> SurveyNames { get; set; }
public IQueryable<string> Names
{
get
{
//Returns SurveyNames after some filtration logic
}
}
}
My problem is that when I pass in this object:
{
"names": ["testname"]
}
The JSON interpreter is trying to deserialize it to match the Names property instead of the SurveyNames property. I know this happens because when removing the implementation of the interface and changing SurveyNames to Names it populates the property fine. Is there any way to get it to serialize to the correct property or do I need to create a translator class that will generate the proper concretion of the INameSet interface?
EDIT: This is with the built-in serializer. If there is a solution with Newtonsoft/JSON.NET that would be fine with me.
JavaScriptSerializer doesn't allow for remapping of names out of the box, so don't use it.
Instead, use Json.NET or DataContractJsonSerializer. In fact, both should already work given the data contract attributes you have applied.
For instance, using Json.NET, if I do:
var page1 = JsonConvert.DeserializeObject<SurveyPage>(json);
Debug.Assert(page1.SurveyNames != null && page1.SurveyNames.SequenceEqual(new string [] { "testname" }));
Then there is no assert. Similarly there is no assert if I do:
var page2 = DataContractJsonSerializerHelper.GetObject<SurveyPage>(json);
Debug.Assert(page2.SurveyNames != null && page2.SurveyNames.SequenceEqual(new string[] { "testname" }));
using the helper class:
public static class DataContractJsonSerializerHelper
{
private static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
public static string GetJson<T>(T obj, DataContractJsonSerializer serializer)
{
using (var memory = new MemoryStream())
{
serializer.WriteObject(memory, obj);
memory.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(memory))
{
return reader.ReadToEnd();
}
}
}
public static string GetJson<T>(T obj) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return GetJson(obj, serializer);
}
public static T GetObject<T>(string json) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return GetObject<T>(json, serializer);
}
public static T GetObject<T>(string json, DataContractJsonSerializer serializer)
{
T obj = default(T);
using (var stream = GenerateStreamFromString(json))
{
obj = (T)serializer.ReadObject(stream);
}
return obj;
}
}
Update
If you really want to continue to use JavaScriptConverter, you can write your own JavaScriptConverter and deserialize each field manually. But it's a bother and I wouldn't recommend it.

Parsing JSON page

Been trying to figure out how to parse out "in_reply_to_status_id_str -> id_str" form the twitter search page:
https://twitter.com/phoenix_search.phoenix?q=hello&headers%5BX-Twitter-Polling%5D=true&headers%5BX-PHX%5D=true&since_id=203194965877194752&include_entities=1&include_available_features=1&contributor_details=true&mode=relevance&query_source=unknown
Anyone that could write a small example to show how it can be done?
Using Json.Net
dynamic jObj = JsonConvert.DeserializeObject(new WebClient().DownloadString("your url"));
foreach (var item in jObj.statuses)
{
Console.WriteLine("{0} {1}", item.in_reply_to_status_id_str, item.id_str);
}
SO here is where I pull my Json, this is where my list gets made, which you all ready have:
public JsonResult AllStatuses() //from the json called in the _client view
{
var buildStatuses = new List<BuildStatus>();
var projects = Client.AllProjects();
foreach (var project in projects)
{
try
{
var buildConfigs = Client.BuildConfigsByProjectId(project.Id);
foreach (var buildConfig in buildConfigs)
{
var b = new BuildStatus();
var build = Client.LastBuildByBuildConfigId(buildConfig.Id);
var status = build.Status; // Used to loop through BuildConfigID's to find which is a FAILURE, SUCCESS, ERROR, or UNKNOWN
var change = Client.LastChangeDetailByBuildConfigId(buildConfig.Id); // Provides the changeID
var changeDetail = Client.ChangeDetailsByChangeId(change.Id); // Provides the username, this one populates the usernames
if (changeDetail != null)
b.user = changeDetail.Username;
b.id = buildConfig.Id.ToString();
// If the date isn't null place the start date in long format
if (build.StartDate != null)
b.date = build.StartDate.ToString();
// If block; set the status based on the BuildconfigID from the var status
if (status.Contains("FAILURE")){
b.status = "FAILURE";
}
else if (status.Contains("SUCCESS")){
b.status = "SUCCESS";
}
else if (status.Contains("ERROR")){
b.status = "ERROR";
}
else{
b.status = "UNKNOWN";
}
buildStatuses.Add(b);
}
} catch { }
}
var query = buildStatuses.OrderBy(x => x.status); // Create a sorted list from Error - Unknown
return Json(query, JsonRequestBehavior.AllowGet);
Then I copied the JsonConverter I linked you too.
On my Website I finally pulled apart the list of Json with.
public JsonResult AllStatuses() //from the json called in the _client view
{
List<Client> clients = storeDB.Clients.Include("Projects").Include("Projects.Builds").ToList();
var buildStatuses = new List<BuildStatus>();
foreach (var client in clients) {
// Network credentials
// Used to get the Json Service request // URL here: client.ClientURL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:81/Status/AllStatuses");
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var responseString = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters((new[] { new DynamicJsonConverter() }));
dynamic obj = serializer.Deserialize(responseString, typeof(object)) as dynamic;
foreach (var objects in obj) // Pull apart the dynamic object
{
var id = objects.id;
var status = objects.status;
var date = objects.date;
var user = objects.user;
var bs = new BuildStatus();
try
{
bs.status = status;
bs.date = date;
bs.id = id;
bs.user = user;
}
catch { throw; }
buildStatuses.Add(bs);
}
}
return Json(buildStatuses, JsonRequestBehavior.AllowGet);
}
Go for a jQuery approach:
var obj = jQuery.parseJSON(jsonString);
alert(obj.in_reply_to_status_id_str.id_str);
You can use this json libraryfor accomplish this.
You could also use the DataContractJsonSerializer class available in .NET once you add a reference to System.Runtime.Serialization.
All you need to do is a create two DataContract classes. Something like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace MyNamespace
{
[DataContract]
public class TwitterObject
{
[DataMember(Name = "statuses")]
public TwitterStatus[] Statuses { get; set; }
}
[DataContract]
public class TwitterStatus
{
[DataMember(Name = "in_reply_to_status_id_str")]
public string InReplyToStatusIdStr { get; set; }
[DataMember(Name = "id_str")]
public string IdStr { get; set; }
}
}
Then from any other method you wish, you just have to use the DataContractJsonSerializer to build your JSON into a .NET object:
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TwitterObject));
// assume the twitterResponse is the JSON you receive
MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(twitterResponse));
var twitterJson = jsonSerializer.ReadObject(memoryStream) as TwitterObject;
There may be some typos, but this should give you the hint. I'm currently working on an extensive synchronization between a server app and a website and this is the method I currently use for JSON communication between the two. I've found the combination of DataContracts and DataContractJsonSerializer is easier to use than 3rd party libraries.

Deserialize JSON with C#

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/

How to convert a List<T> to specific Json format

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;}
}

Categories