简体   繁体   中英

Converting ordinary string to object

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?

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

live demo


Disclaimer: As Jodrell noticed it return a "RootObject".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM