json'u kullanmak için .net web api kullanıyorum ve açılı olarak ön tarafa döndürüyorum. Json, bir nesne veya bir dizi olabilir. Kodum şu anda sadece nesne değil dizi için çalışıyor. İçeriğin bir nesne mi yoksa dizi mi olduğunu belirlemek için bir yol bulmalıyım.Json sonuçlarının nesne mi yoksa dizi mi olduğunu belirleyin
İşte benim kod
public HttpResponseMessage Get(string id)
{
string singleFilePath = String.Format("{0}/../Data/phones/{1}.json", AssemblyDirectory, id);
List<Phone> phones = new List<Phone>();
Phone phone = new Phone();
JsonSerializer serailizer = new JsonSerializer();
using (StreamReader json = File.OpenText(singleFilePath))
{
using (JsonTextReader reader = new JsonTextReader(json))
{
//if array do this
phones = serailizer.Deserialize<List<Phone>>(reader);
//if object do this
phone = serailizer.Deserialize<Phone>(reader);
}
}
HttpResponseMessage response = Request.CreateResponse<List<Phone>>(HttpStatusCode.OK, phones);
return response;
}
Bunu yapmanın yukarıda olmayabilir en iyi yoldur. Sadece şu an olduğum yer.
İlk charcter'i kontrol edebilirsiniz, isArray = content [0] == '[' –
@ johnny5 İyi bir lib kullanılabilir olduğunda elle ayrıştırma genellikle iyi bir fikir değildir. Durumda nokta, beyaz boşluk olup olmadığını kontrol etmeyi unutmuşsunuz :) '' [] "' geçerli bir json dizisidir. – dcastro
bu yüzden bir cevap olarak göndermedim, çünkü bir hack ama notu layık. –