locked
JSON String from WCF RRS feed

  • Question

  • User-515951590 posted

    I have one operation contract

    public string GetPlayers() {     List<Person> players = new List<Person>();     players.Add(new  Person { FirstName="Peyton", LastName="Manning", Age=35 } );     players.Add(new  Person { FirstName="Drew", LastName="Brees", Age=31 } );     players.Add(new  Person { FirstName="Brett", LastName="Favre", Age=58 } );

     System.Web.Script.Serialization.JavaScriptSerializer oSerializer =          new System.Web.Script.Serialization.JavaScriptSerializer(); string sJSON = oSerializer.Serialize(players); return sJSON;

    }

    This return json string as

    [{"Age":35,"FirstName":"Peyton","LastName":"Manning"},   {"Age":31,"FirstName":"Drew","LastName":"Brees"},   {"Age":58,"FirstName":"Brett","LastName":"Favre"}]

    IS THERE ANY WAY TO RETURN STRING AS

    {Players : [{"Age":35,"FirstName":"Peyton","LastName":"Manning"},   {"Age":31,"FirstName":"Drew","LastName":"Brees"},   {"Age":58,"FirstName":"Brett","LastName":"Favre"}] };

    Thursday, May 30, 2013 5:20 AM

Answers

  • User-610330605 posted

    You have to wrap up the list inside a property of another class as Shown below.

    public class PlayerCollection
    {
        public List<Person> Players { get; set; }
    } 

    You have to set the list of players to the Players property of this class and the service should return that instance of PlayersCollection. Change the implementation as shown below.

    public string GetPlayers() 
    {
        var playerCollection = new PlayerCollection();
        var players = new List<Person>();
        players.Add(new  Person { FirstName="Peyton", LastName="Manning", Age=35 } );
        players.Add(new  Person { FirstName="Drew", LastName="Brees", Age=31 } );
        players.Add(new  Person { FirstName="Brett", LastName="Favre", Age=58 } );
        playerCollection.Players = players;
    
        var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(playerCollection);
        return sJSON;
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 30, 2013 7:04 AM