简体   繁体   中英

Characters added and wrong output during serialization with Json.NET

JSON.NET seems to serialize my code into what appear to be strings, instead of objects. Here's an example of what it returns:

  "{\"kvk_nummer\":11111111,\"onderneming\":\"berijf B.V.\",\"vestigingsplaats\":\"AMSTERDAM\",\"actief\":1}"

It also adds strange backslashes, I tried to get rid of them, but none of the answers I've found seemed to have helped. Here is the code that returns the string.

getregister r = new getregister
    {
    kvk_nummer = col1, //contains an 8 digit number
    onderneming = checkTotaal[col1], //contains a name
    vestigingsplaats = checkTotaal2[col1], //contains a location
    actief = 1 // bool that represents wether the company is active or not
    };
    yield return JsonConvert.SerializeObject(r);

How can i get JSON.NET to output an object, instead of some JSON strings?

Looks like you're confusing some stuff. Taken from Serialization (C#)

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

When you serialize into JSON, you get a JSON representation of your object. Which is a string representation. Taken from the JSON Wikipedia page :

JavaScript Object Notation or JSON is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).

In short: your code is doing what you're asking it to do. As far as the slashes go: those are escape characters. If you want (JSON.NET to return) an object, return the object you're creating ( r ).

return new getregister
{
    kvk_nummer = col1, //contains an 8 digit number
    onderneming = checkTotaal[col1], //contains a name
    vestigingsplaats = checkTotaal2[col1], //contains a location
    actief = 1 // bool that represents wether the company is active or not
};

If you're looking for a way to have JSON.NET return an object, you should take a look into Deserializing it. Since that takes the string-representation (JSON) for your object, and turns it back into an actual object for you.

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