I'd prefer to use Microsofts System.Runtime.Serialization.Json.DataContractJsonSerializer to serialize my objects in JSON so I do not have to reference any third party assemblies.
I'm trying to serialize arrays into a JSON string. There maybe just 1 array, with every other entry being the name and other being the value.
e.g.[ "name1", "value1", "name2", "value2" ]
I wish to serialize so that the name and value appears a pair in the JSON string
e.g.
the array in .NET is [ "name1", "value1", "name2", "value2" ]
becomes
{
"name1": "value1",
"name2": "value2"
}
I have successfully achieved this with the JSON.NET JsonTextWriter by looping through the 2 arrays and adding to then using the
jsonWriter.WritePropertyName(namesAndValues[i].ToString());
j开发者_JS百科sonWriter.WriteValue(namesAndValues[i+1]);
I'm trying to do the same thing with Microsofts DataContractJsonSerializer but it doesn't seem to have the same flexibility. Is there some way?
I know I can use the JSON.NET source code itself but I'd rather use a Microsoft class if possible.
DataContractJsonSerializer is designed to serialise classes to JSON. To get the kind of output you want you would have to serialise a class with 2 properties called name1 and name2 that have the values of value1 and value2. Is the format of the JSON completely fixed, if you just want a collection of key value pairs you could trun your array into a Dictionary<string,string>
and serialise that using DataContractJsonSerializer. However you would end up with something like:
{
{
"Key":"name1",
"Value":"value1"
},
{
"Key":"name2",
"Value":"value2"
}
}
I.e. an array of key value pairs.
精彩评论