Incremental JSON Parsing in C#
I have to admit I'm not as familiar with the JavaScriptSerializer, but if you're open to use JSON.net, it has a JsonReader
that acts much like a DataReader
.
using(var jsonReader = new JsonTextReader(myTextReader)){
while(jsonReader.Read()){
//evaluate the current node and whether it's the name you want
if(jsonReader.TokenType.PropertyName=="add"){
//do what you want
} else {
//break out of loop.
}
}
}
How to parse huge JSON file as stream in Json.NET?
This should resolve your problem. Basically it works just like your initial code except it's only deserializing object when the reader hits the {
character in the stream and otherwise it's just skipping to the next one until it finds another start object token.
JsonSerializer serializer = new JsonSerializer();
MyObject o;
using (FileStream s = File.Open("bigfile.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
while (reader.Read())
{
// deserialize only when there's "{" character in the stream
if (reader.TokenType == JsonToken.StartObject)
{
o = serializer.Deserialize<MyObject>(reader);
}
}
}
How do I incrementally serialize and deserialize JSON with ServiceStack?
Define your types:
public class Object
{
public int t { get; set; }
public string whatever { get; set; }
public string str { get; set; }
}
public class RootObject
{
public int number { get; set; }
public Object object { get; set; }
}
Then just deserialize it:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
//do what you want
UPDATE
You didn't say it's dynamic, for such parsing there is many solutions.
Check the following:
Using JSON.NET for dynamic JSON parsing
Using C# 4.0 and dynamic to parse JSON
Deserialize JSON into C# dynamic object?
Parse JSON block with dynamic variables
Turning JSON into a ExpandoObject
To handle a dynamic type: use dynamic
, to handle dynamic data such as XML or JSON use ExpandoObject
.
UPDATE 2
Using Anonymous types to deserialize JSON data
UPDATE 3
Will this work for you:
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = SimpleJson.DeserializeObject<IDictionary<string, object>>(json);
var yourObject = deserialized["object"] as IDictionary<string, object>;
if (yourObject != null)
{
var tValue = yourObject.GetValue("t");
var whateverValue = yourObject.GetValue("whatever");
var strValue = yourObject.GetValue("str");
}
public static object GetValue(this IDictionary<string,object> yourObject, string propertyName)
{
return yourObject.FirstOrDefault(p => p.Key == propertyName).Value;
}
Final result:
Or change to the following
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
UPDATE 4 - SERVICE STACK
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = JsonObject.Parse(json);
var yourObject = deserialized.Get<IDictionary<string, object>>("object");
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
Result:
Parsing large JSON file in .NET
As you've correctly diagnosed in your update, the issue is that the JSON has a closing ]
followed immediately by an opening [
to start the next set. This format makes the JSON invalid when taken as a whole, and that is why Json.NET throws an error.
Fortunately, this problem seems to come up often enough that Json.NET actually has a special setting to deal with it. If you use a JsonTextReader
directly to read the JSON, you can set the SupportMultipleContent
flag to true
, and then use a loop to deserialize each item individually.
This should allow you to process the non-standard JSON successfully and in a memory efficient manner, regardless of how many arrays there are or how many items in each array.
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead(stringUrl))
using (StreamReader streamReader = new StreamReader(stream))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
reader.SupportMultipleContent = true;
var serializer = new JsonSerializer();
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
Contact c = serializer.Deserialize<Contact>(reader);
Console.WriteLine(c.FirstName + " " + c.LastName);
}
}
}
Full demo here: https://dotnetfiddle.net/2TQa8p
how can to parse in c# JSON with dynamic key using JSON.NET or any other package
Use Dictionary<string, Datas>
for property Customer
in Stat
class,
public class Stat
{
public string connection_status { get; set; }
public string operation_status { get; set; }
public Dictionary<string, Datas> Customer { get; set; }
}
Usage:
GetAccountBalanceResponseModel model = JsonConvert.DeserializeObject<GetAccountBalanceResponseModel>(json);
foreach (var item in model.status.Customer)
{
Console.WriteLine("Key: " + item.Key);
Console.WriteLine("Id: " + item.Value.id);
Console.WriteLine("FirstName: " + item.Value.FirstName);
Console.WriteLine("LastName: " + item.Value.LastName);
Console.WriteLine();
}
Output:
Related Topics
No Console Output When Using Allocconsole and Target Architecture X86
JSON.Net - Serialize Property Name Without Quotes
What Are Some Reasons Networkstream.Read Would Hang/Block
Inheritance with Base Class Constructor with Parameters
Force Download of a File on Web Server - Asp .Net C#
How to Convert an Iso8601 Timespan to a C# Timespan
Capturing Binary Output from Process.Standardoutput
Call Non-Static Method in Server-Side from Client-Side Using Javsscript
How to Find the State of Numlock, Capslock and Scrolllock in .Net
Getting Specified Node Values from Xml Document
C# Adding Button with Value at Runtime
What Happens If I Don't Call Dispose on the Pen Object
Lock (Monitor) Internal Implementation in .Net
Mono Https Webrequest Fails with "The Authentication or Decryption Has Failed"