Parse Json string in C#
I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:
EDIT: I changed the code so it supports reading your json file (array)
Code to parse:
void Main()
{
var json = System.IO.File.ReadAllText(@"d:\test.json");
var objects = JArray.Parse(json); // parse as array
foreach(JObject root in objects)
{
foreach(KeyValuePair<String, JToken> app in root)
{
var appName = app.Key;
var description = (String)app.Value["Description"];
var value = (String)app.Value["Value"];
Console.WriteLine(appName);
Console.WriteLine(description);
Console.WriteLine(value);
Console.WriteLine("\n");
}
}
}
Output:
AppName
Lorem ipsum dolor sit amet
1
AnotherAppName
consectetur adipisicing elit
String
ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text
Application
Ut enim ad minim veniam
100
LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ
BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.
How to parse this json result without making class in C#
Thx everyone, i just figure it out my self.
This is what i do.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public async Task<string> CheckDevice(string id)
{
var uri = new Uri(string.Format(Constant.CheckDevicesRegistration + "id=" + id, string.Empty));
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var jsonData = (JObject)JsonConvert.DeserializeObject(result);
var message = jsonData["response"]["message"].Value<string>();
resultService = message;
}
}
catch
{
resultService = "Connection-Error";
}
return resultService;
}
Easiest way to parse JSON response
Follow these steps:
- Convert your JSON to C# using json2csharp.com;
- Create a class file and put the above generated code in there;
- Add the
Newtonsoft.Json
library to your project using the Nuget Package Manager; Convert the JSON received from your service using this code:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
(Feel free to rename RootObject
to something more meaningful to you. The other classes should remain unchanged.)
C# Parsing JSON String
After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.
Details details = new Details();
public class Details
{
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public string realname { get; set; }
public string personaname { get; set; }
public string steamid { get; set; }
}
private void GetSteamDetails()
{
var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
avatar = SteamDetails.response.players[1].avatar.ToString();
personaname = SteamDetails.response.players[1].personaname.ToString();
}
How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?
Json.NET does this...
string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
More examples: Serializing Collections with Json.NET
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; }
}
How can I parse some JSON dynamically without knowing JSON values?
The code below is perhaps not the most elegant nor complete, but I think it will get you going. I would start by using the JObject.Parse()
from the Newtonsoft.Json.Linq
namespace and take it from there.
JObject root = JObject.Parse(info);
string symbol = root["symbol"].ToObject<string>();
foreach (JToken toplevel in root["callExpDateMap"].Children())
{
foreach (JToken nextlevel in toplevel.Children())
{
foreach (JToken bottomlevel in nextlevel.Children())
{
foreach (JToken jToken in bottomlevel.Children())
{
JArray jArray = jToken as JArray;
foreach (var arrayElement in jArray)
{
InfoObject infoObject = arrayElement.ToObject<InfoObject>();
Console.WriteLine(infoObject.putCall);
Console.WriteLine(infoObject.exchangeName);
Console.WriteLine(infoObject.multiplier);
}
}
}
}
}
public class InfoObject
{
public string putCall { get; set; }
public string symbol { get; set; }
public string description { get; set; }
public string exchangeName { get; set; }
// ...
public int multiplier { get; set; }
// ...
}
Related Topics
Remove Duplicates in the List Using Linq
Why Does Property Set Throw Stackoverflow Exception
How to Convert Utf-8 Byte[] to String
What's the Fastest Way to Read a Text File Line-By-Line
Why Is the Console Window Closing Immediately Once Displayed My Output
Why Is There a Default Instance of Every Form in Vb.Net But Not in C#
Given a Datetime Object, How to Get an Iso 8601 Date in String Format
Parallel Foreach With Asynchronous Lambda
How to Read a Text File Reversely With Iterator in C#
What Are the Default Access Modifiers in C#
Find and Extract a Number from a String
How to Prevent the App from Terminating When I Close the Startup Form
Best Practice to Call Configureawait For All Server-Side Code
How to Query an Ntp Server Using C#
How to Evaluate C# Code Dynamically
Parse Datetime With Time Zone of Form Pst/Cest/Utc/Etc