Reputation: 1285
{"ItemName":"8","Id":1}
{"ItemName":"9","Id":2}
I am reading json file from blob, each line has above format and row is not even split by comma and also there is no square brackets in a file.
When i try setting SupportMultipleContent true in jsontextreader i get following exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ValueDTO]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'ItemName', line 1, position 12.
Alternatively if parsing of such json is not possible then how would I configure a datafactory in azure to have the file in correct json format.
Code:
using (var sr = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
jsonTextReader.SupportMultipleContent = true;
while (jsonTextReader.Read())
{
var data = serializer.Deserialize<T>(jsonTextReader);
result.Add(data);
}
}
}
Json has no explicit \n character
Upvotes: 1
Views: 3837
Reputation: 35767
Following code works on my machine. I am using Newtonsoft.Json
version 12.0.3
targeting netcoreapp3.0
.
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = @"
{'ItemName':'8','Id':1}
{'ItemName':'9','Id':2}
";
var items = new List<Item>();
var serializer = new JsonSerializer();
using (var sr = new StringReader(json))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
jsonTextReader.SupportMultipleContent = true;
while (jsonTextReader.Read())
{
var data = serializer.Deserialize<Item>(jsonTextReader);
items.Add(data);
}
}
}
foreach (Item item in items)
{
Console.WriteLine($"{item.Id}: {item.ItemName}");
}
}
}
public class Item
{
public string ItemName { get; set; }
public int Id { get; set; }
}
}
Upvotes: 4
Reputation: 11
Please use Jsonconvert deserialization method.
List<object> myDeserializedObjList = (List<object>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent, typeof(List<object>));
Upvotes: 1
Reputation: 38767
Each line of your JSON is, by itself, a JSON object. You do not have a JSON array containing all of the objects.
To read it, you just need to rewrite your method to deserialize each line individually:
private static List<ValueDTO> LoadItems(Stream stream)
{
var result = new List<ValueDTO>();
using (var reader = new StreamReader(stream))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
result.Add(JsonConvert.DeserializeObject<ValueDTO>(line));
}
}
}
return result;
}
Upvotes: 4