如何序列化原始json字段?

时间:2021-03-11 00:57:05

I have a field in the db that store a json string and I want that when I return it in a json result that will be returned as json raw data and not warped with quotes as string.

我在db中有一个存储json字符串的字段,当我在json结果中返回它时,我想要它将作为json原始数据返回,而不是用引号作为字符串扭曲。

UPDATE 1(More Info): if you looking at the images field it contain a raw json string value
but after serialize it with the JsonResult it get warped with quotes that it ok because is a type of String, how can i tell the serializer to treat the images field as a raw json data?

更新1(更多信息):如果你看图像字段它包含一个原始的json字符串值但是在用JsonResult序列化之后它会被引号扭曲,因为它是一种String,我怎么能告诉序列化器将图像字段视为原始json数据?

        var db = new ModelsContainer();
        var res = db.Images.OrderByDescending(i=>i.DateCreated).Skip(skip).Take(take).Select( i => new {
            id = i.Id,
            dateCreated = i.DateCreated,
            images =  i.Images ,
            user = new {
                id = i.User.Id,
                facebookId = i.User.FacebookId,
                displayName = i.User.DisplayName
            },
            tags = i.Tags.Select( t => t.Value )
        }).ToList();

        return Json(res, JsonRequestBehavior.AllowGet);

     [
        {
            "id":"5c528e88-f3a7-4b30-9746-980867325fd1",
            "dateCreated":"\/Date(1364381593000)\/",
            "images":"[{\"source\":\"http://localhost:9242/images/f4956702/6d34/42db/b28a/397d0eaf3097.jpg\",\"width\":237,\"height\":237},{\"source\":\"http://localhost:9242/images/87d47041/1522/4d10/9325/105851aae259.jpg\",\"width\":633,\"height\":633},{\"source\":\"http://localhost:9242/images/2a639272/9067/42fb/83ee/e88f0a0878f8.jpg\",\"width\":547,\"height\":547},{\"source\":\"http://localhost:9242/images/37caa7b2/e183/4efc/96eb/487e556501b2.jpg\",\"width\":1024,\"height\":1024}]",
            "user":{"id":"ea39616d-6ff9-424b-b99b-7bee53e674bb","facebookId":"608215901","displayName":"Yonathan Garti"},
            "tags":["test","test","test"]
        },
        ...
    ]

2 个解决方案

#1


8  

With Json.net you can define your own JsonConverters to apply a specific serialization behavior. You may apply it for a specific type or, if you have a view model, a specific property.

使用Json.net,您可以定义自己的JsonConverters以应用特定的序列化行为。您可以将其应用于特定类型,或者,如果您有视图模型,则可以应用特定属性。

In your case you want to write the Images-string as a raw-string using JsonWriter.WriteRawValue.

在您的情况下,您希望使用JsonWriter.WriteRawValue将Images-string写为原始字符串。

Ie.

IE浏览器。

public class PlainJsonStringConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue((string)value);
    }
}

public class MyViewModel
{
    public string id { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(PlainJsonStringConverter))]
    public string images { get; set; }
    /* ...  */
}

#2


-1  

You will need to unserialize the data. C# offers a class to handle JSON data.

您需要反序列化数据。 C#提供了一个处理JSON数据的类。

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

Excerpt from http://msdn.microsoft.com/en-us/library/bb412179.aspx :

摘自http://msdn.microsoft.com/en-us/library/bb412179.aspx:

Normally, JSON serialization and deserialization is handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly - this is the scenario that this topic demonstrates.

通常,当您在通过启用AJAX的端点上公开的服务操作中使用数据协定类型时,Windows Communication Foundation(WCF)会自动处理JSON序列化和反序列化。但是,在某些情况下,您可能需要直接使用JSON数据 - 这是本主题演示的方案。

//Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

stream1.Position = 0;   
Person p2 = (Person)ser.ReadObject(stream1);

//Show the results.

Console.Write("Deserialized back, got name=");
Console.Write(p2.name);
Console.Write(", age=");
Console.WriteLine(p2.age);

#1


8  

With Json.net you can define your own JsonConverters to apply a specific serialization behavior. You may apply it for a specific type or, if you have a view model, a specific property.

使用Json.net,您可以定义自己的JsonConverters以应用特定的序列化行为。您可以将其应用于特定类型,或者,如果您有视图模型,则可以应用特定属性。

In your case you want to write the Images-string as a raw-string using JsonWriter.WriteRawValue.

在您的情况下,您希望使用JsonWriter.WriteRawValue将Images-string写为原始字符串。

Ie.

IE浏览器。

public class PlainJsonStringConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue((string)value);
    }
}

public class MyViewModel
{
    public string id { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(PlainJsonStringConverter))]
    public string images { get; set; }
    /* ...  */
}

#2


-1  

You will need to unserialize the data. C# offers a class to handle JSON data.

您需要反序列化数据。 C#提供了一个处理JSON数据的类。

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

Excerpt from http://msdn.microsoft.com/en-us/library/bb412179.aspx :

摘自http://msdn.microsoft.com/en-us/library/bb412179.aspx:

Normally, JSON serialization and deserialization is handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly - this is the scenario that this topic demonstrates.

通常,当您在通过启用AJAX的端点上公开的服务操作中使用数据协定类型时,Windows Communication Foundation(WCF)会自动处理JSON序列化和反序列化。但是,在某些情况下,您可能需要直接使用JSON数据 - 这是本主题演示的方案。

//Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

stream1.Position = 0;   
Person p2 = (Person)ser.ReadObject(stream1);

//Show the results.

Console.Write("Deserialized back, got name=");
Console.Write(p2.name);
Console.Write(", age=");
Console.WriteLine(p2.age);