2017-01-26 2 views
2

я следующие данные JSON в виде строкиJsonConvert.DeserializeObject ошибка при преобразовании JSON строки в C#

string data = "{\"STARTTIME\":\"12:00\",\"ENGINNEERSIGNATURE\":\"Engineer Signature .jpg\",\"OVERNIGHTS\":\"1\",\"SIGNOUT\":\"Yes\"}" 
var dataOut = JsonConvert.DeserializeObject<Dictionary<string, string>>(data); 

Мне нужно, чтобы преобразовать его в объект словарь, но я получаю следующее сообщение об ошибке при попытке

Newtonsoft.Json.JsonSerializationException: Error converting value "{"STARTTIME":"12:00","ENGINNEERSIGNATURE":"Engineer Signature .jpg","OVERNIGHTS":"1","SIGNOUT":"Yes"}" to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'. Path '', line 1, position 119. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.String,System.String]. 
    at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable (System.Object value, System.Type initialType, System.Type targetType) [0x00062] in <2781d1b198634655944cdefb18b3309b>:0 
    at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast (System.Object initialValue, System.Globalization.CultureInfo culture, System.Type targetType) [0x00031] in <2781d1b198634655944cdefb18b3309b>:0 
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType (Newtonsoft.Json.JsonReader reader, System.Object value, System.Globalization.CultureInfo culture, Newtonsoft.Json.Serialization.JsonContract contract, System.Type targetType) [0x0008d] in <2781d1b198634655944cdefb18b3309b>:0 
    --- End of inner exception stack trace --- 
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType (Newtonsoft.Json.JsonReader reader, System.Object value, System.Globalization.CultureInfo culture, Newtonsoft.Json.Serialization.JsonContract contract, System.Type targetType) [0x000bd] in <2781d1b198634655944cdefb18b3309b>:0 
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x000d7] in <2781d1b198634655944cdefb18b3309b>:0 
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x0007a] in <2781d1b198634655944cdefb18b3309b>:0 

Где я буду ошибся

+0

добавить свою ошибку также – Thili77

+0

http://stackoverflow.com/help/how-to-ask «поиск и исследование ... и следить за то, что вы найдете. Даже если вы этого не сделаете найти полезный ответ в другом месте на сайте, в том числе ссылки на связанные вопросы, которые не помогли, могут помочь другим понять, как ваш вопрос отличается от остальных ». «Включить любые сообщения об ошибках» «Если можно создать живой пример проблемы, которую вы можете связать с« – AndyJ

+0

сообщение об ошибке добавлено :) –

ответ

0

Попытайтесь использовать Dictionary<string,object>, это позволит использовать значение JSON любого типа объекта. Dictionary<string,string> будет работать только в том случае, если все значения объекта JSON имеют строку типа. Но если есть какое-либо другое значение, например массив или вложенный объект JSON, он будет терпеть неудачу.

0

Не могу точно сказать, что там не так, но можете ли вы сказать мне, что эта маленькая программа печатает на первых двух строках в консоли, запускается на одной машине с вашим примером кода, я могу определить две возможные проблемы с версией Newtonsoft с вами местная культура

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Reflection; 
using System.Threading; 
using Newtonsoft.Json; 

namespace test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //Your culture 
      Console.WriteLine("Your Culture:" + Thread.CurrentThread.CurrentCulture.Name); 
      //your JsonConvert Assembly version 
      Console.WriteLine("JsonConvert Assembly" + JsonConvertVersion()); 
      //I guess you have welsh culture, by your nickname 
      //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("cy-GB"); 
      var stringified = "{\"STARTTIME\":\"12:00\",\"ENGINNEERSIGNATURE\":\"Engineer Signature .jpg\",\"OVERNIGHTS\":\"1\",\"SIGNOUT\":\"Yes\"}"; 
      Console.WriteLine(stringified); 
      //Invariant culture witch shoudn't fail 
      var settings = new JsonSerializerSettings() { Culture = System.Globalization.CultureInfo.InvariantCulture }; 
      var dataOut = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringified, settings); 
      //welsh culture, case I think that is what you are using, but for me is working 
      var settings2 = new JsonSerializerSettings() { Culture = new System.Globalization.CultureInfo("cy-GB", false) };//Welsh 
      var dataOut2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringified, settings2); 
      //object with invariant culture 
      Console.WriteLine(dataOut); 
      //object with welsh culture 
      Console.WriteLine(dataOut2); 
      Console.WriteLine(JsonConvert.SerializeObject(dataOut)); 
      Console.WriteLine(JsonConvert.SerializeObject(dataOut2)); 

     } 
     public static string JsonConvertVersion() 
     { 
      Assembly asm = Assembly.GetAssembly(typeof(JsonConvert)); 
      FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); 
      return String.Format("{0}.{1}", fvi.FileMajorPart, fvi.FileMinorPart); 

     } 
    } 
} 
Смежные вопросы