Parsing Json Using Json.Net

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{

const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";


static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

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);
}
}
}

Json.NET - deserialising and parsing json data in winforms

You should use the class which is corresponding to the whole input string and not only to some part of it. So you can use class like below:

public class InputObject{
public TitlesClass titles {get;set;}
public SigneesClass signees {get;set;}
}

public class TitlesClass {
public string Title {get;set;}
public string SubTitle {get;set;}
}

public class SigneesClass {
public string SigneeTitle0 {get;set;}
public string SigneeTitle1 {get;set;}
public string SigneeTitle2 {get;set;}
}

public void ReadFormDataFile(string fileLocation)
{
string tmp = File.ReadAllText(fileLocation);
InputObject parsedObject = JsonConvert.DeserializeObject<InputObject>(tmp);
}

Parsing multi-level JSON with JSON.NET

You can use JSON.Net's JObject. Here's an example:

var jsonString = "{\"method\":\"someMehtod\",   \"content\":{\"oneObject\":\"can be a very complicated object\"},   \"somotherthing\":\"someOtherValue\"}";
var obj = JsonConvert.DeserializeObject<JObject>(jsonString);
Console.WriteLine(obj["content"]["oneObject"]); // will print "can be a very complicated object"

dotnet fiddle demo available here

Parse JSON to C# object using NewtonSoft JSON.net

Define a class and deserialize it:

var results =  JsonConvert.DeserializeObject<RootObject>(response.Content);   

public class LineMatch
{
public int line { get; set; }
public string context { get; set; }
public string escaped { get; set; }
}

public class Match
{
public string field { get; set; }
public string fieldLabel { get; set; }
public List<LineMatch> lineMatches { get; set; }
public int count { get; set; }
}

public class Hit
{
public string name { get; set; }
public string className { get; set; }
public string tableLabel { get; set; }
public List<Match> matches { get; set; }
public string sysId { get; set; }
public long modified { get; set; }
}

public class Result
{
public string recordType { get; set; }
public List<Hit> hits { get; set; }
public string tableLabel { get; set; }
}

public class RootObject
{
public List<Result> result { get; set; }
}

Parsing JSON key/value pairs with JSON.NET

You can deserialize to Dictionary<string, string>

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach(var kv in dict)
{
Console.WriteLine(kv.Key + ":" + kv.Value);
}

Since JObject implements IDictionary, you can also simply use JObject.Parse

var dict = JObject.Parse(@"{""1"":""Name 1"",""2"":""Name 2""}");

Parse Json in VB.NET with Newtonsoft Json.net


Dim json As String = rawresp
Dim jsonObject As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.Linq.JObject.Parse(json)
Dim jsonArray As JArray = jsonObject("result")

For Each item As JObject In jsonArray
textboxLast.Text = item.SelectToken("Last").ToString
Next

It has to do with the format of the JSON. it is not an array, but an object that contains an array, so you have to first parse the object, and then take the array out of it to parse properly. You missed that one extra step, which I added in above code snippet

How to parse JSON data that doesn't have a title using Json.NET

If you're doing something as simple as grabbing one value from the JSON you might want to simply:

string thejson = @"{
""error_code"": 0,
""access_token"": ""*******************"",
""expires_in"": 7200
}";

JObject jobj = JObject.Parse(thejson);

string theToken = jobj["access_token"].ToString();

How to parse a json array json.net

Not wanting to use classes is weird but not impossible.

var json = reader.ReadToEnd();
var objects = JsonConvert.DeserializeObject<dynamic[]>(json);
var lvi = new ListViewItem(new string[] { (string)objects[i].label, (string)objects[i].value });


Related Topics



Leave a reply



Submit