简体   繁体   中英

How to JSON Data Format JavaScript Serializer in ASP.NET

I am writing an ASP.NET web service. I made the connection to SQL Server. The web service is using a JavaScript serializer. My JSON format:

[{"ID":1,"TCKN":"19","Adi":"zzz","Soyadi":"aa"},
{"ID":2,"TCKN":"99","Adi":"user","Soyadi":"user"}]

But I want this JSON format:

"users": [
    {
            "ID": "1",
            "TCKN": "19",
            "Adi": "zzz",
            "Soyadi": "aa"
    },
    {
            "ID": "2",
            "TCKN": "99",
            "Adi": "user",
            "Soyadi": "user"
    },]

WebServices.cs

  [WebMethod]
public string getTumKullanici()
{
    JavaScriptSerializer jss = new JavaScriptSerializer();
    var json = "";
    var tumKullanicilar = from result in mydb.Kullanicilars
                          select result;

    json = jss.Serialize(tumKullanicilar);

    return json;
}

Whenever you're dealing with JSON data that you need to serialize into C#, go to Json2CSharp

Using that site I've got your C# data model:

public class RootObject
{
    public int ID { get; set; }
    public string TCKN { get; set; }
    public string Adi { get; set; }
    public string Soyadi { get; set; }
}

Next you're going to need JSON.NET

You can get that by opening the nuget package manager and searching Newtonsoft.Json

Or use the Package manager console

PM> Install-Package Newtonsoft.Json 

Next you're going to need to deserialize that JSON..

string json = @"{""ID"":1,""TCKN"":""19"",""Adi"":""zzz"",""Soyadi"":""aa""},{""ID"":2,""TCKN"":""99"",""Adi"":""user"",""Soyadi"":""user""}]";

RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

And if you never need to serialize the C# object back into JSON... You can do this.

string backToJson = JsonConvert.SerializeObject(root);

EDIT

You can achieve nesting the under users by wrapping your original object with another class:

public class Users
{
    public int ID { get; set; }
    public string TCKN { get; set; }
    public string Adi { get; set; }
    public string Soyadi { get; set; }
}

public class Root
{
    public List<User> Users {get;set;}
}

var root = new Root { Users = mydb.Kullanicilars.ToList() };

JsonConvert.SerializeObject(root);

My understanding is that the way the JSON is displayed lacks of new line chars etc - that's completely normal and desired, as extra characters are useless for services. To make the JSON more readable to humans, you could use tools that enable formatting, as fe addon to Notepad++ or some webapp. But for general use as data in computing I would stick to raw format without the tabulators and new lines.

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