2015-07-13 2 views
1

Я подключаю REST api из C#. У меня есть ответ Json с несколькими объектами ошибки с разными именами, но все объекты имеют одинаковые переменные: название, сообщение и отображение.У меня есть ответ JSon, имеющий объекты с разными именами, но все объекты имеют одинаковые переменные

Число объектов изменяется с каждым запросом API (REST), имена объектов в ответе различаются в зависимости от запросов. Но переменные в каждой ошибке такие же, как указано выше.

Информация, которая мне нужна из этого ответа, является только текстом сообщения, но это будет приемлемо, если я получу список объектов ошибок, чтобы я мог читать сообщения из-за ошибок.

Вот ответ JSon:

{ 
    "errors": { 
     "missingparameter_general_paymenttype": { 
      "title": "", 
      "message": "You must enter 'general_paymenttype'.", 
      "display": "" 
     }, 
     "missingparameter_contact_title": { 
      "title": "", 
      "message": "You must enter 'contact_title'.", 
      "display": "" 
     }, 
     "missingparameter_contact_firstname": { 
      "title": "", 
      "message": "You must enter 'contact_firstname'.", 
      "display": "" 
     }, 
     "missingparameter_contact_lastname": { 
      "title": "", 
      "message": "You must enter 'contact_lastname'.", 
      "display": "" 
     }, 
     "missingparameter_contact_email": { 
      "title": "", 
      "message": "You must enter 'contact_email'.", 
      "display": "" 
     }, 
     "missingparameter_contact_telephone": { 
      "title": "", 
      "message": "You must enter 'contact_telephone'.", 
      "display": "" 
     }, 
     "invalidparameter_pricing_currency": { 
      "title": "", 
      "message": "Invalid value for 'pricing_currency'.", 
      "display": "" 
     }, 
     "missingparameter_pricing_saleprice": { 
      "title": "", 
      "message": "You must enter 'pricing_saleprice'.", 
      "display": "" 
     }, 
     "missingparameter_transfers": { 
      "title": "", 
      "message": "You must enter 'transfers'.", 
      "display": "" 
     } 
    } 
} 
+0

'Newtonsoft.Json.JsonConvert. DeserializeObject <Словарь > (jsonStr) 'Конечно, вы должны определить класс, содержащий словарь –

+0

, вы хотите преобразовать json в объекты C#? – gypsyCoder

+0

Да @gypsyCoder – nicejani80

ответ

1
class Errors 
{ 
    public Dictionary<string, Error> errors { get; set; } 
    public class Error 
    { 
     public string title { get; set; } 
     public string message { get; set; } 
     public string display { get; set; } 
    } 
} 

static void Main(string[] args) 
{ 
    string errorText = @"{ 
""errors"": { 
""missingparameter_general_paymenttype"": { 
""title"": """", 
""message"": ""You must enter 'general_paymenttype'."", 
""display"": """" 
}, 
""missingparameter_contact_title"": { 
""title"": """", 
""message"": ""You must enter 'contact_title'."", 
""display"": """" 
}, 
""missingparameter_contact_firstname"": { 
""title"": """", 
""message"": ""You must enter 'contact_firstname'."", 
""display"": """" 
}, 
""missingparameter_contact_lastname"": { 
""title"": """", 
""message"": ""You must enter 'contact_lastname'."", 
""display"": """" 
}, 
""missingparameter_contact_email"": { 
""title"": """", 
""message"": ""You must enter 'contact_email'."", 
""display"": """" 
}, 
""missingparameter_contact_telephone"": { 
""title"": """", 
""message"": ""You must enter 'contact_telephone'."", 
""display"": """" 
}, 
""invalidparameter_pricing_currency"": { 
""title"": """", 
""message"": ""Invalid value for 'pricing_currency'."", 
""display"": """" 
}, 
""missingparameter_pricing_saleprice"": { 
""title"": """", 
""message"": ""You must enter 'pricing_saleprice'."", 
""display"": """" 
}, 
""missingparameter_transfers"": { 
""title"": """", 
""message"": ""You must enter 'transfers'."", 
""display"": """" 
} 
}}"; 
    var error = JsonConvert.DeserializeObject<Errors>(errorText); 
    foreach (var kv in error.errors) 
    { 
     Console.WriteLine(kv.Value.message); 
    } 
} 

Вам нужно добавить использовать Newtonsoft.Json, или вы можете также использовать Regex, как этот

string patten = @"""message""\s*:\s*""([^""]*)"""; 
foreach (Match match in Regex.Matches(errorText, patten)) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
}