Parse JSON String in C#

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 json string in c#

But parsing would be the right way, to get the right data out of your string.
Example with using Newtonsoft.Json:

var objects = JsonConvert.DeserializeObject<List<MyObj>>(jsonText);

With the class:

public class MyObj
{
public string id_employe { get; set; }
}

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 to read parse JSON String in C#

The first part seems to be an int, you have multiple way to remove it:

var withoutNumberPrefix = new string(input.SkipWhile(c=> Char.IsDigit(c)).ToArray());
var fixedSize = input.Substring(2, input.Length - 2);
var always42 = input.TrimStart(new[] { '4', '2' });

Once you have done that you have a List<string>, where the first value is the type and the second the "array" of that type.

var listResults = JsonConvert.DeserializeObject<string[]>(fixedSize);

You can deserialize the second part:

var result = JsonConvert.DeserializeObject<Dictionary<int,CtiAgentes>>(listResults[1]);

Into the matching type, created with a simple copy past using those tool

How to auto-generate a C# class file from a JSON string
:

public partial class CtiAgentes
{
[JsonProperty("id_agents_interface")]
public int IdAgentsInterface { get; set; }

[JsonProperty("agent")]
public int Agent { get; set; }

[JsonProperty("interface")]
public string Interface { get; set; }

[JsonProperty("logintime")]
public DateTimeOffset Logintime { get; set; }

[JsonProperty("pausetime")]
public DateTimeOffset? Pausetime { get; set; }

[JsonProperty("paused")]
public string Paused { get; set; }

[JsonProperty("id_pausa")]
public object IdPausa { get; set; }

[JsonProperty("invalid")]
public string Invalid { get; set; }

[JsonProperty("invalidtime")]
public object Invalidtime { get; set; }

[JsonProperty("fullcontact")]
public string Fullcontact { get; set; }

[JsonProperty("textoterminal")]
public string Textoterminal { get; set; }
}

In this Live demo, you will notice that there is no string manipulation except "remove the 42". Not backslash not quote were modify. It's a json hardcoded in a string Store Hardcoded JSON string to variable

Nota bene:
I used DateTimeOffset for Pausetime and Logintime, because there where no timezone in that input. You can use Datetime but it will be nice to know if it's gmt or localized data.

For all the null value I choosed object. because I don't know the type. And that will go boom sooner or later with data. One can assume that id is a int and invalid time a DateTimeOffSet, but I can't make that decision.

Convert JSON String To C# Object

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

  class Test {

String test;

String getTest() { return test; }
void setTest(String test) { this.test = test; }

}

Then your deserialization code would be:

   JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx

What is the simplest C# function to parse a JSON string into an object?

DataContractJsonSerializer serializer = 
new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);

You could also use the JavaScriptSerializer, but DataContractJsonSerializer is supposedly better able to handle complex types.

Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer since it is hard baked for WCF.

Convert JSON String to JSON Object c#

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation.

C# Parsing Json string returned from GraphQL - Monday.com

You have to pass in a string to DeserializeObject instead of a JSON object.

Another way would be get your JSON mapped to a POCO types as follows, easy way to do is on Visual Studio (Copy your JSON contents, on Visual Studio create a new empty class -> Edit-> Past Special -> Paste JSON as classes)

public class LogsRoot
{
public Activity_Logs[] activity_logs { get; set; }
}

public class Activity_Logs
{
public string data { get; set; }
}

public class DataRoot
{
public long board_id { get; set; }
public string group_id { get; set; }
public bool is_top_group { get; set; }
public long pulse_id { get; set; }
public string pulse_name { get; set; }
public string column_id { get; set; }
public string column_type { get; set; }
public string column_title { get; set; }
public Value value { get; set; }
public Previous_Value previous_value { get; set; }
public bool is_column_with_hide_permissions { get; set; }
public string previous_textual_value { get; set; }
}

public class Value
{
public Column_Settings column_settings { get; set; }
}

public class Column_Settings
{
public bool includePulseInSubject { get; set; }
public bool ccPulse { get; set; }
public string bccList { get; set; }
}

public class Previous_Value
{
public string email { get; set; }
public string text { get; set; }
public DateTime changed_at { get; set; }
public Column_Settings1 column_settings { get; set; }
}

public class Column_Settings1
{
public bool includePulseInSubject { get; set; }
public bool ccPulse { get; set; }
public string bccList { get; set; }
}

Then load the JSON and manipulate as follows,

var json = File.ReadAllText("data.json");
var rootLogs = JsonConvert.DeserializeObject<LogsRoot>(json);

Dictionary<string, string> fields = new Dictionary<string, string>();

foreach (var logJson in rootLogs.activity_logs)
{
var log = JsonConvert.DeserializeObject<DataRoot>(logJson.data);
fields.Add(log.column_id, log.value.column_settings.bccList + log.value.column_settings.ccPulse);
fields.Add(log.pulse_name, log.value.column_settings.bccList + log.value.column_settings.ccPulse);
fields.Add(log.previous_value.email, log.value.column_settings.bccList + log.value.column_settings.ccPulse);
fields.Add(log.previous_textual_value, log.value.column_settings.bccList + log.value.column_settings.ccPulse);
}


Related Topics



Leave a reply



Submit