Reputation: 73
Is it possible to convert ordinary string like:
"Data: {
id: '288dsbshbdas8dsdsb',
data: '2pm'
}"
to:
Data: {
id: '288dsbshbdas8dsdsb',
data: '2pm'
}
Have tried like that:
string input = "Data: {id: '288dsbshbdas8dsdsb', data: '2pm'};
var output = Convert.ChangeType(input, TypeCode.Object);
But this still returns string?
Upvotes: 0
Views: 111
Reputation: 2057
Using NewtonSoft JsonTextWriter, and JsonTextReader You can easly write and read this kind of string.
For writing your must use JsonTextWriter
property:
writer.QuoteName = false;
writer.QuoteChar = '\'';
To read to custom configuration is needed.
using System;
using System.IO;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var objSource= new RootObject{
Data= new Data{
id="123456",
data="FooBar"
}
};
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter);
writer.QuoteName = false;
writer.QuoteChar = '\'';
serializer.Serialize(writer, objSource);
var input= stringWriter.ToString();
Console.WriteLine(input);
JsonTextReader reader = new JsonTextReader(new StringReader(input));
var result = serializer.Deserialize<RootObject>(reader);
result.Dump();
}
public class Data
{
public string id { get; set; }
public string data { get; set; }
}
public class RootObject
{
public Data Data { get; set; }
}
}
The writer will return {Data:{id:'123456',data:'FooBar'}}
instead of Data:{id:'123456',data:'FooBar'}
Notice the extra {}
around the string.
The string manipulation needed to get from one too the other is minor enought.
Upvotes: 3