简体   繁体   中英

convert json data to angular object in angular2

Webmethod code

[System.Web.Services.WebMethod]
 public static string getBatch(string program,string location, string createdby)
 {
    List<batTerSec> Masterobj = new List<batTerSec>();        
                    batTerSec temp = new batTerSec();
                    temp.batch = tmobj;
                    temp.term = tmobj1;
                    temp.section = tmobj2;
                    Masterobj.Add(temp);       
    return JsonConvert.SerializeObject(Masterobj);
}
public class batTerSec
{
    public string batch { get; set; }
    public string term { get; set; }
    public string section { get; set; }    }

json data

  { "d": "[{\"batch\":\"5\",\"term\":\"TERM V\",\"section\":\"Section I\"},{\"batch\":\"5\",\"term\":\"TERM VI\",\"section\":\"Section I\"},{\"batch\":\"5\",\"term\":\"TERM VII\",\"section\":\"Section I\"},{\"batch\":\"6\",\"term\":\"TERM I\",\"section\":\"Section I\"},{\"batch\":\"6\",\"term\":\"TERM II\",\"section\":\"Section I\"}]" } 

Required like following

 [
    { 'batch': '28', 'term': 'Term I', 'section': 'Section I' },
    { 'batch': '28', 'term': 'Term I', 'section': 'Section II' }      
]

how to convert Newtonsoft json to angular2 object ?

You have a JSON-encoded string in you JSON so you just need to parse it twice:

let final= JSON.parse(data.d);

You just need to use the final value to get the content of your JSON.

However , it is weird that you are receiving data encoded like this, maybe you could tweak the server to get properly-encoded JSON object and not a string.

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