Error converting value to type system

When performing an AJAX request I am getting the following error: Error converting value {null} to type 'System.Int32'. Path '[5].tabID', line 1, position 331. The error occurs on the second li...

When performing an AJAX request I am getting the following error:

Error converting value {null} to type ‘System.Int32’. Path ‘[5].tabID’, line 1, position 331.

The error occurs on the second line of my processRequest (...)

public void ProcessRequest (HttpContext context) { 
    string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();
    List<ElementToUpdate> elements = JsonConvert.DeserializeObject<List<ElementToUpdate>>(strJson);

    // (...)
}

The debugger says that this the content of strJson:

[{
    "bmk": "132M1",
    "state": "off",
    "type": "motor",
    "tabID": 8
}, {
    "bmk": "158M1",
    "state": "off",
    "type": "motor",
    "tabID": 8
}, {
    "bmk": "194M1",
    "state": "off",
    "type": "motor",
    "tabID": 8
}, {
    "bmk": "198M1",
    "state": "on",
    "type": "motor",
    "tabID": 8
}, {
    "bmk": "202M1",
    "state": "off",
    "type": "motor",
    "tabID": 8
}, {
    "bmk": "test-m",
    "state": "on",
    "type": "motor",
    "tabID": null
}, {
    "bmk": "158M1-2",
    "state": "off",
    "type": "motor",
    "tabID": 2
}, {
    "bmk": "100M1",
    "state": "on_right",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "152M1",
    "state": "on",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "192M1",
    "state": "on_left",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "196M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "2000M1",
    "state": "on_left",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "74M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "76M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "80M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "82M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "86M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "90M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "94M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "95M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "96M1",
    "state": "off",
    "type": "screwconveyor",
    "tabID": 8
}, {
    "bmk": "102Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "104Y1",
    "state": "open",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "112Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "114Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "120Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "122Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "128Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "146Y1_2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "148Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "156Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "180Y1",
    "state": "open",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "182Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "184Y1",
    "state": "open",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "206Y1",
    "state": "open",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "208Y1",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "72Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "78Y2",
    "state": "open",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "84Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "88Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "92Y2",
    "state": "closed",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "95_1Y1",
    "state": "blocked",
    "type": "ventile",
    "tabID": 8
}, {
    "bmk": "17H1",
    "state": "on",
    "type": "lamp",
    "tabID": 8
}, {
    "bmk": "l1",
    "state": "on",
    "type": "lamp",
    "tabID": 8
}, {
    "bmk": "17H1-2",
    "state": "on",
    "type": "lamp",
    "tabID": 2
}, {
    "bmk": "106M1",
    "state": "on",
    "type": "elevator",
    "tabID": 8
}, {
    "bmk": "154M1",
    "state": "off",
    "type": "elevator",
    "tabID": 8
}, {
    "bmk": "164M1",
    "state": "off",
    "type": "rotaryvalve",
    "tabID": 8
}]

The class ElementToUpdate is

public class ElementToUpdate
{
public ElementType type;
public String bmk;
public string state;
public int tabID;

public ElementToUpdate()
{
}

public ElementToUpdate(ElementType type, String bmk, string state, int tabID)
{
    this.type = type;
    this.bmk = bmk;
    this.state = state;
    this.tabID = tabID;
}
}

So my question is: How to resolve this issue? If I understand the error message correctly, then it says that tabID of the 5th json object in the serialized array is null. But as you can see it isn’t. Moreover ElementToUpdate.tabID isn’t an Int32 but an int. Did I miss something?

The solution

In fact, my JSON string contained an element whose tabID was null. I somehow overlooked this because firstly my JSON string wasn’t formatted when I checked and secondly because [5] means «6th element of the array» (which I claimed to know actually).

Just recently out of nowhere I get the error shown below in my console output.

Socket Opened = System.EventArgs
Websocket Error Event = System.IO.IOException: The read operation failed, see inner exception. ---> Newtonsoft.Json.JsonSerializationException: Error converting value "" to type 'System.Guid'. Path 'client_oid', line 1, position 163. ---> System.ArgumentException: Could not cast or convert from System.String to System.Guid.
   at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
   at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at CoinbasePro.WebSocket.WebSocket.WebSocket_MessageReceived(Object sender, MessageReceivedEventArgs e)
   at WebSocket4Net.WebSocket.FireMessageReceived(String message)
   at WebSocket4Net.Command.Text.ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
   at WebSocket4Net.WebSocket.OnDataReceived(Byte[] data, Int32 offset, Int32 length)
   at WebSocket4Net.WebSocket.client_DataReceived(Object sender, DataEventArgs e)
   at SuperSocket.ClientEngine.ClientSession.OnDataReceived(Byte[] data, Int32 offset, Int32 length)
   at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.OnDataRead(IAsyncResult result)
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
   at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   --- End of inner exception stack trace ---
   at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
   at System.Net.Security.SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
   at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.StartRead()
Socket Opened = System.EventArgs
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in System.dll
Error converting value "" to type 'System.Guid'. Path 'client_oid', line 1, position 163.

It just started happening recently with no code changes on my end that would cause it.
I tried different versions going back to 1.0.23, nothing works.

It seems like a issue with Coinbase since it just started happening out of nowhere.

I’m going to try a fresh project and see it still happens, but in the mean time, maybe you already know how to fix it. I thought about going and modifying Newton soft to get it to work again but that is kinda my last resort.

  • Remove From My Forums
  • Question

  • An exception of type

    ‘Newtonsoft.Json.JsonSerializationException’ occurred in Newtonsoft.Json.DLL but was not handled in user code

    Additional information: Error converting value {null} to type ‘System.Boolean’. Path ‘collection[8].downloadable’, line 1, position 22866.

    or

    converter value {null} from path ‘track[40].like_count

    public class User
        {
            public string full_name { get; set; }
            public string country { get; set; }
            public string city { get; set; }
            public int tracks_count { get; set; }
            public int followers_count { get; set; }
            public int followings_count { get; set; }
            public int public_favorites_count { get; set; }
            public int groups_count { get; set; }
            public string description { get; set; }
            public string plan { get; set; }
            public int id { get; set; }
            public string uri { get; set; }
            public string username { get; set; }
            public string kind { get; set; }
            public string permalink { get; set; }
            public string permalink_url { get; set; }
            public string first_name { get; set; }
            public string avatar_url { get; set; }
            public string last_modified { get; set; }
        }
    
        public class __invalid_type__0
        {
            public string urn { get; set; }
            public int entry_time { get; set; }
            public string visual_url { get; set; }
            public object link { get; set; }
        }
    
        public class Visuals2
        {
            public __invalid_type__0 __invalid_name__0 { get; set; }
        }
    
        public class Visuals
        {
            public string urn { get; set; }
            public bool enabled { get; set; }
            public Visuals2 visuals { get; set; }
            public object tracking { get; set; }
        }
    
        public class Collection
        {
            public User user { get; set; }
            public int user_id { get; set; }
            public string genre { get; set; }
            public string tag_list { get; set; }
            public int duration { get; set; }
            public bool downloadable { get; set; }
            public bool streamable { get; set; }
            public int original_content_size { get; set; }
            public bool commentable { get; set; }
            public string sharing { get; set; }
            public bool @public { get; set; }
            public string created_at { get; set; }
            public string updated_at { get; set; }
            public string isrc { get; set; }
            public string state { get; set; }
            public bool embeddable { get; set; }
            public string embeddable_by { get; set; }
            public string license { get; set; }
            public string waveform_url { get; set; }
            public bool feedable { get; set; }
            public string label_name { get; set; }
            public string release_date { get; set; }
            public bool has_downloads_left { get; set; }
            public string purchase_title { get; set; }
            public string purchase_url { get; set; }
            public string policy { get; set; }
            public string monetization_model { get; set; }
            public Visuals visuals { get; set; }
            public string permalink { get; set; }
            public string title { get; set; }
            public string description { get; set; }
            public string track_type { get; set; }
            public string last_modified { get; set; }
            public string artwork_url { get; set; }
            public int id { get; set; }
            public string kind { get; set; }
            public int comment_count { get; set; }
            public int download_count { get; set; }
            public string uri { get; set; }
            public string stream_url { get; set; }
            public int playback_count { get; set; }
            public string download_url { get; set; }
            public object secret_token { get; set; }
            public int reposts_count { get; set; }
            public string permalink_url { get; set; }
            public int likes_count { get; set; }
        }
    
        public class Facet2
        {
            public string filter { get; set; }
            public int count { get; set; }
            public string value { get; set; }
        }
    
        public class Facet
        {
            public string name { get; set; }
            public List<Facet2> facets { get; set; }
        }
    
        public class RootObject
        {
            public List<Collection> collection { get; set; }
            public List<Facet> facets { get; set; }
            public int total_results { get; set; }
            public string qid { get; set; }
            public string query_urn { get; set; }
            public string next_href { get; set; }
        }

    use Json. How to fix it?

    var query_items = await query.SoundCloudTrack(link);
                    Next_search_Uri = null;
                    if (query_items != null)
                    {
                        var tr = JsonConvert.DeserializeObject<TrackSoundCloud.RootObject>(query_items);
                        SoundcloudItemsSource.Source = tr.tracks;

    e.g

    ‘collection[8].downloadable’ is null then replace it into ‘false’

    ‘track[40].like_count  is null then replace it into ‘1’

Answers

  • Hello Le Thien Hoang,

    >>use Json. How to fix it?

    Try to set these two property to be nullable as:

      public int? Reference { get; set; }

    Or use «JsonProperty» attribute:

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    
    public int Reference { get; set; }
    

    The first approach would return null value, the second one would populate the null field with the default value, e.g. 0 for int and false for bool.

    Regards.

    • Marked as answer by

      Tuesday, June 30, 2015 4:58 AM

Hello friends,

here am facing little bit problem while deserializing json string to list

json string : Result of restful service

""[{\"UName\":\"prasad\",\"LastName\":\"k\",\"FirstName\":\"sai\"}]""

and i want to convert this json string to list of «_TempUser» class

my list :

public class _TempUser
      {

          public string UName
          {
              get;
              set;

          }


          public string LastName
          {
              get;
              set;
          }

          public string FirstName
          {
              get;
              set;
          }
      }

Error is

Error converting value "[{"UName":"prasad","LastName":"k","FirstName":"sai"}]" to type 'System.Collections.Generic.List`1[loginServices.Login_Service+_TempUser]'. Path '', line 1, position 70.

code in my restful service

List<_TempUser> List = new List<_TempUser>();

_TempUser ud = new _TempUser();

           ud.UName = "prasad";
           ud.FirstName = "sai";
           ud.LastName = "k";
           List.Add(ud);

           string json = JsonConvert.SerializeObject(List);

           return json;

code : for calling restful service

 var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://IpAddress:Post/Login/RestServiceName.svc/RestMethoName");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json =JsonConvert.SerializeObject(Req);
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string result =  streamReader.ReadToEnd();
                  


                    List<_TempUser> List = new List<_TempUser>();  

                    List = JsonConvert.DeserializeObject<List<_TempUser>>result   
                }

            }

any modifications or suggestions plz?


its an temporary solution, if any once got exact solution plz let me know.

 using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string result =  streamReader.ReadToEnd();
                  


 
  

  string s = result.Replace(@"", string.Empty);




                  string final= s.Trim().Substring(1,(s.Length)-2);




                    List<_TempUser> List = new List<_TempUser>();  
 
                    List = JsonConvert.DeserializeObject<list><_tempuser>>(final)
               }
</_tempuser></list>

its working fine for me ;)

if u wana check ur json string valid or not just use this link

http://jsonlint.com/[^]

Validate the type of data that you are sending in the header I am referring to MediaTypeWithQualityHeaderValue («text / plain») <- since it can be an «application / Json» or «text / json», this type can change the serialization.

In my case I changed it to text / plain and it worked

I hope to be helpful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

IdentityServer4 has a strange way of returning roles. If there is only one role, the property is a string:

{
    "sub": "55568182-9273-4c6f-8d61-6555f7f02551",
    "role": "role001"
}

But if there is more than one role, the property is an array of strings:

{
    "sub": "55568182-9273-4c6f-8d61-6555f7f02551",
    "role": [
        "role001",
        "role002"
    ]
}

If the property is a string, and you try to serialize this into an IEnumerable<string>, you get the following error:

Could not cast or convert from System.String to System.Collections.Generic.IEnumerable`1[System.String].

JsonSerializationException: Error converting value “xxx” to type ‘System.Collections.Generic.IEnumerable`1[System.String]

Or

Could not cast or convert from System.String to System.String[].

JsonSerializationException: Error converting value “xxx” to type ‘System.String[]’

To serialize this into a model class, you will need to implement a JsonConverter, which is a custom converter that, in this case, checks if the property is one object or several before serializing.

STEP 1: IMPLEMENT THE CUSTOM CONVERTER

This JsonConverter checks the property before serializing to see if the property is an array or not. If not, it will output the single item as an array:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace MyCode
{
  internal class CustomArrayConverter<T> : JsonConverter
  {
    public override bool CanConvert(Type objectType)
    {
      return (objectType == typeof(List<T>));
    }

    public override object ReadJson(
      JsonReader reader,
      Type objectType,
      object existingValue,
      JsonSerializer serializer)
    {
      JToken token = JToken.Load(reader);
      if (token.Type == JTokenType.Array)
        return token.ToObject<List<T>>();
      return new List<T> { token.ToObjec<T>() };
    }

    public override bool CanWrite
    {
      get
      {
        return false;
      }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      throw new NotImplementedException();
    }
  }
}

STEP 2: USE THE CUSTOM CONVERTER IN THE MODEL CLASS:

The custom converter is used as a property on the attribute:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace MyCode
{
  [Serializable]
  public class UserInfoModel
  {
    [JsonProperty("sub")]
    public string ID { get; set; }

    [JsonProperty("role")]
    [JsonConverter(typeof(CustomArrayConverter<string>))]
    public IEnumerable<string> Roles { get; set; }
  }
}

The CustomArrayConverter will work on any type.

MORE TO READ: 

  • Newtonsoft JsonConverter
  • Json Arrays from W3CSchools

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.

This entry was posted in .net, .NET Core, c#, General .NET and tagged JSON, JsonConverter, Newtonsoft. Bookmark the permalink.

24 / 40 / 14

Регистрация: 27.03.2014

Сообщений: 754

1

25.07.2015, 11:02. Показов 2362. Ответов 3


Раньше делал это стандартными Нет средствами — ошибок не было. Стало необходимым юзать либу по сабжу для кросплатформености, так вылазиет ошибка

e = {Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type ‘System.Single’. Path ‘[579].np_stazh’, line 1, position 310134. —> System.InvalidCastException: Null object cannot be converted to a value type.
at System.Convert.Chan…

По тексту джайсона не смог найти противоречивых данных.
np_stazh в классе десериализации это float

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Ev_Hyper

Заблокирован

25.07.2015, 12:12

2

jenokizm, json и созданные классы покажите



1



870 / 720 / 304

Регистрация: 15.04.2013

Сообщений: 2,047

Записей в блоге: 5

25.07.2015, 17:35

3

jenokizm,
Измените данные тогда если нельзя опубликовать и выложите все здесь на форуме



0



jenokizm

24 / 40 / 14

Регистрация: 27.03.2014

Сообщений: 754

25.07.2015, 18:23

 [ТС]

4

Проблема решена! Благодарю Ev_Hyper за ответ в личку. Дело было в том что некоторые np_stazh = null, шарп в отличии от JS такие неточности не прощает)
Варианты решения:
1. в бд

SQL
1
2
UPDATE teachers SET np_stazh = '0' 
WHERE np_stazh IS NULL

2. перед отдачей в php как то так

PHP
1
2
3
4
5
6
7
8
9
10
$json_response = array();
      while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
      {
          //$data[] = $row; // допишем строку из выборки как новый элемент результирующего массива
          if ($row['np_stazh'] == NULL) $row['np_stazh'] = 0;
          array_push($json_response, $row); //отправить в конечный массив
 
      }
        //print_r($data);
        echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK); // и отдаём как json



1



Make your tabID nullable:

public int? tabID;

Value null could not be deserialized to integer.
That’s your 6-th part of json (or 5-th starting with 0):

{"bmk":"test-m","state":"on","type":"motor","tabID":null}

You could see, that tabID is null there.

Depending on your use case, you may also want to consider having the JSON Serializer ignore nulls

Example:

Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";

string included = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { });

// {
//   "Name": "Bad Boys III",
//   "Description": "It's no Bad Boys",
//   "Classification": null,
//   "Studio": null,
//   "ReleaseDate": null,
//   "ReleaseCountries": null
// }

string ignored = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

// {
//   "Name": "Bad Boys III",
//   "Description": "It's no Bad Boys"
// }

Tags:

C#

.Net

Json

Json.Net

Deserialization

Related

  • Remove From My Forums
  • Question

  • Hi,

    I have written a function to get event logs from multiple machine as below. But getting error ‘Cannot convert value to type System.String.’ when passing a text file of computers using $comp = Get-Content -path ‘file path’.

    $Comp = Import-csv -Path ‘CSV path’

    Get-EventLogReport -Computer $Comp -Before ’10/10/2016′ -After 10/09/2016 -LogName ‘System’ -CSVPath C:3.csv -Newest 5

    Scripts:   

    Function Get-EventLogReport
    {
    [CmdletBinding()]
    param
    (

            [Parameter(Mandatory=$true)][string]$Computers,
            [Parameter(Mandatory=$true)][string]$Before,
            [Parameter(Mandatory=$true)][string]$After,
            [Parameter(Mandatory=$true)][string]$CSVPath,
            [Parameter(Mandatory=$true)][string]$LogName,
            [Parameter(Mandatory=$false)][int]$Newest

            
    )
    foreach ($Computer in $Computers)
    {
    Write-verbose ‘Processing the Event Logs on each server’ -Verbose
    if (!($Newest))
    {
    Get-EventLog -ComputerName $Computers -LogName $LogName -EntryType Warning,Error | Select-Object -Property * | Export-CSV -Path $CSVPath -NoTypeInformation
    }
    else
    {
    Get-EventLog -ComputerName $Computers -LogName $LogName -Newest $Newest -EntryType Warning,Error | Select-Object -Property * | Export-CSV -Path $CSVPath -NoTypeInformation
    }
    }
    Write-Verbose ‘Event log is processed and exported to CSV file’ -Verbose
    }

    I am sure issue is with foreach but unable to fix it since morning.

    Script is working fine when i am using -computername $env:computername

    Thanks in advance

    Roushan

Answers

  • Since $Computers is an array, use [String[]].


    Richard Mueller — MVP Enterprise Mobility (Identity and Access)

    • Proposed as answer by

      Monday, October 17, 2016 12:52 PM

    • Marked as answer by
      Roushan_K
      Monday, October 17, 2016 4:30 PM

Понравилась статья? Поделить с друзьями:
  • Error converting to execution character set illegal byte sequence
  • Error converting one or more entries
  • Error converting data type varchar to float перевод
  • Error converting data type varchar to datetime
  • Error converting data type varchar to date