Parsing JSON Files with JSON.NET - c#

I'm new to C# so I don't know how JSON Parsing in C# much. So I'm using JSON.net at the moment, so this is what I got:
WebClient c = new WebClient();
var data = c.DownloadString("http://media1.clubpenguin.com/play/en/web_service/game_configs/furniture_items.json");
JObject o = JObject.Parse(data);
button3.Text = "" + o["furniture_item_id"];
Is there any other way to parse JSON files with the JSON URL?

try
WebClient client = new WebClient();
string getString = client.DownloadString("http://media1.clubpenguin.com/play/en/web_service/game_configs/furniture_items.json");
JavaScriptSerializer serializer = new JavaScriptSerializer();
var listOfFurniture = serializer.Deserialize<List<Furniture>>(getString);
public class Furniture
{
public int furniture_item_id { get; set; }
}
There are many furniture_item_id's returned by the webclient. I've created a simple object that holds that value. 'listOfFurniture' is a List of type Furniture.

dynamic json = JsonConvert.DeserializeObject(data);
You can then access json as array by using an index or a key:
var someval = json["furniture_item_id"];
Note:
In case the request was not successful and thus you do not have any response to parse, this will probably end up in an JsonParseException so you might want to catch that.

Related

How to convert this json string to jobject

How to convert this json string to Jobject
"{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
I need it convert to Jobject like this because i need it to post data to website api . Example :
JObject concac = new JObject();
concac1["id"] = 373697;
concac1["username"] = "luckygirlxxx123";
concac1["counter_rechecking"] = 0;
concac1["user_id"] = 76131;
concac1["fb_id"] = "100047460285611";
Because It inside USER that i dont know how to create jobject with that
this code might help you.
public static void Main(string[] args)
{
string jsonData = "{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
var details = JObject.Parse(jsonData);
Console.WriteLine(string.Concat(details["user"]["id"], " " + details["user"]["username"]));
}
The simplest way is by giving those JSON values to the contracture of the object
public JObject(int id, string username, int user_id ....)
then you declare object and you pass values to it
JObject concac = new JObject(concac1["id"], concac1["username"], concac1["user_id"]..... );
The second way is JSON Serialization And Deserialization In C#

Newtonsoft Object serialized to String. JObject instance expected

Hi so am trying to parse this JSON line but i got some others that are like this in files thats why i want to automate this so i can remove the invalid lines to make the file a valid JSON for reading, The problem is that the JSON contains multiple JSON in 1 line
Example:
{"item":"value"}{"anotheritem":"value"}
Is there anyway to remove
{"anotheritem":"value"}
So it turns in to a valid JSON that is readable to start parsing the files
I tried doing using StreamReader cause there in a file i have multiple files that contain these invalid JSON
So i got it to be able to detect the Invalid JSON but for some reason i can't get it to read the JSON so i can use .remove to remove the invalid line
using (StreamReader r = new StreamReader(itemDir))
{
string json = r.ReadToEnd();
if (json.Contains("anotheritem"))
{
JObject NoGood = JObject.FromObject(json);
MessageBox.Show(NoGood.ToString());
}
}
The Error:
Object serialized to String. JObject instance expected.
Thank you all for your time and help.
If each object are side by side without space or any other character, you can convert your string to an json array.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
string arrayValue = "[" + value.Replace("}{", "},{") + "]";
var array = JArray.Parse(arrayValue);
var goopArray = array.OfType<JObject>().Where(o => o.Property("anotheritem") == null);
Edit : see my second answer. More robust solution. More modern. And support dotnet core builtin json serializer.
Json.Net
Even better solution, Json.NET have a builtin feature for this exact scenario. See Read Multiple Fragments With JsonReader
The JsonTextReader have a property SupportMultipleContent that allow to read consecutive items when set to true
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var reader = new JsonTextReader(new System.IO.StringReader(value));
reader.SupportMultipleContent = true;
var list = new List<JObject>();
while (reader.Read())
{
var item = JObject.Load(reader);
list.Add(item);
}
System.Text.Json
If you want to use System.Text.Json, it's also acheivable. They are no SupportMultipleContent property but Utf8JsonReader will do the job for you.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var bytes = Encoding.UTF8.GetBytes(value).AsSpan();
var list = new List<JsonDocument>();
while (bytes.Length != 0)
{
var reader = new Utf8JsonReader(bytes);
var item = JsonDocument.ParseValue(ref reader);
list.Add(item);
bytes = bytes.Slice((int) reader.BytesConsumed);
}

Remove new lines in JSON string using Newtonsoft JSON.NET

I am using Newtonsoft JSON.NET to create a dynamic JSON object which looks fine, but is unrecognizable when I send it to a REST API. My best guess is there are new lines in the JSON string which is breaking the process the API uses to parse the data. Is there a way to ensure all new lines are removed from the JSON data I am sending?
dynamic MyPerson = new JObject();
MyPerson.username = "CodeMonkey";
MyPerson.first_name = "Monkey";
MyPerson.last_name = "banana";
MyPerson.email_address = "bananacrazy#monkey.com";
MyPerson.is_active = true;
string PersonData = JsonConvert.SerializeObject(MyPerson);
The JSON it is returning if I use Response.Write is:
{"username":"CodeMonkey","first_name":"Monkey","last_name":"Banana","email_address":"monkey#bananacrazy.com","is_active":true}

How can i access any key inside of json string via C#?

My question is simple but i can not do that. i wanna get value of "soap:Body" from below string by C#code?
{"soap:Envelope":{"xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:soap":"http://www.w3.org/2003/05/soap-envelope","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","soap:Body":{"ToplamaResponse":{"xmlns":"http://tempuri.org/","ToplamaResult":156758}}}}
You can also use the Framework class JavaScriptSerializer if you do not want to use an external library.
string json = #"...";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var o = serializer.Deserialize<dynamic>(json);
var body = o["soap:Envelope"]["soap:Body"];
You can do it easily by using Json.NET
dynamic data = JObject.Parse("{'soap:Envelope':{'xmlns:xsd':'http://www.w3.org/2001/XMLSchema','xmlns:soap':'http://www.w3.org/2003/05/soap-envelope','xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','soap:Body':{'ToplamaResponse':{'xmlns':'http://tempuri.org/','ToplamaResult':156758}}}}");
string soap_body = data["soap:Envelope"]["soap:Body"];
There is a simple example in the JObject.Parse documentation
string json = #"{
"soap:Envelope": {
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soap:Body": {
"ToplamaResponse": {
"xmlns": "http://tempuri.org/",
"ToplamaResult": 156758
}
}
}
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["soap:Envelope"]["soap:Body"]);
And if you want to manipulate the value of "soap:Body" do the same thing :)

C# deserialization

How to deserialize with keyvaluepair the above json
string stations = [{"2":false,"1":"Aforre","0":"WS6"},{"2":false,"1":"Alodtau","0":"WS3"},{"2":false,"1":"Balimo Station","0":"WS36"}]
I what like this
var get = js.Deserialize<Dictionary<string,dynamic>>(stations);
try this:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic value = serializer.DeserializeObject(stations);
and you can access objects like:
var a = value[0]["0"];
and a will have "WS6" (according to your JSON)
The JSON shown is an array. You might try desetializing to:
Dictionary<string, object>[]
i.e.
var get = js.Deserialize<Dictionary<string,object>[]>(stations);
One of the best option is create a class that consist of all keyvalue pair and then deserialize json string to the object of created class
You can try using dynamic variable as following:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic serializevalues = serializer.DeserializeObject(stations);
var valueof1 = serializevalues[0]["1"];
Response.Write(valueof1);
The above will print output "Aforre'.

Categories