How to read specific Json object from Json string in C#? - c#

Following is the JSON string:
{
"ios_info": {
"serialNumber": "F2LLMBNJFFF",
"imeiNumber": "01388400413235",
"meid": "",
"iccID": "8901410427640096045",
"firstUnbrickDate": "11/27/13",
"lastUnbrickDate": "11/27/13",
"unbricked": "true",
"unlocked": "false",
"productVersion": "7.1.2",
"initialActivationPolicyID": "23",
"initialActivationPolicyDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"appliedActivationPolicyID": "23",
"appliedActivationDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"nextTetherPolicyID": "23",
"nextTetherPolicyDetails": "US AT&T Puerto Rico and US Virgin Islands Activation Policy",
"macAddress": "ACFDEC6C988A",
"bluetoothMacAddress": "AC:FD:EC:6C:98:8B",
"partDescription": "IPHONE 5S SPACE GRAY 64GB-USA"
},
"fmi": {
"#attributes": {
"version": "1",
"deviceCount": "1"
},
"fmipLockStatusDevice": {
"#attributes": {
"serial": "F2LLMBNJFFFQ",
"imei": "013884004132355",
"isLocked": "true",
"isLost": "false"
}
}
},
"product_info": {
"serialNumber": "F2LLMBNJFFFQ",
"warrantyStatus": "Apple Limited Warranty",
"coverageEndDate": "11/25/14",
"coverageStartDate": "11/26/13",
"daysRemaining": "498",
"estimatedPurchaseDate": "11/26/13",
"purchaseCountry": "United States",
"registrationDate": "11/26/13",
"imageURL": "http://service.info.apple.com/parts/service_parts/na.gif",
"explodedViewURL": "http://service.info.apple.com/manuals-ssol.html",
"manualURL": "http://service.info.apple.com/manuals-ssol.html",
"productDescription": "iPhone 5S",
"configDescription": "IPHONE 5S GRAY 64GB GSM",
"slaGroupDescription": "",
"contractCoverageEndDate": "11/25/15",
"contractCoverageStartDate": "11/26/13",
"contractType": "C1",
"laborCovered": "Y",
"limitedWarranty": "Y",
"partCovered": "Y",
"notes": "Covered by AppleCare+ - Incidents Available",
"acPlusFlag": "Y",
"consumerLawInfo": {
"serviceType": "",
"popMandatory": "",
"allowedPartType": ""
}
}
}
Following Reads ALLJSON in Key:Value and displays in table format But i need only specific object i.e FMI section of json string only:
private string GetKeyValuePairs(string jsonString)
{
var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
string sdict = string.Empty;
string fmitxt = string.Empty;
string fmitxt2 = string.Empty;
foreach (string key in resDict.Keys)
{
sdict += "<tr><td> " + key + "</td> " + (resDict[key].GetType() == typeof(Newtonsoft.Json.Linq.JObject) ? "<td>" + GetKeyValuePairs(resDict[key].ToString()) + "</td></tr>" : "<td>" + resDict[key].ToString() + "</td></tr>");
}
return sdict;
}
Problem:
I want to read ALL the content of "fmi" section only. and display in key:Value. table format
NOTE:
I am using Framework 3.5 hence cant use dynamic keyword.
Any idea?

I'd recommend that you work with it as a JObject directly; this is the class you'd be using behind-the-scenes if you were using dynamic. Also, you need to separate out the selection of fmi from the normal path done in the recursive calls: here I have it in Main.
void Main()
{
var resObj = JsonConvert.DeserializeObject<JObject>(jsonString);
var result = GetKeyValuePairs((JObject)resObj["fmi"]);
}
private string GetKeyValuePairs(JObject resObj)
{
string sDict = string.Empty;
string fmitxt = string.Empty;
string fmitxt2 = string.Empty;
foreach (var pair in resObj)
{
sDict += "<tr><td> " + pair.Key + "</td>";
if (pair.Value is JObject)
sDict += "<td>" + GetKeyValuePairs((JObject)pair.Value) + "</td></tr>";
else
sDict += "<td>" + pair.Value.ToString() + "</td></tr>";
}
return sDict;
}

Since you are not deserializing this into a "strong typed" object you can do something like this:
var fmi = JsonConvert.DeserializeObject<Dictionary<string,object>>(str)["fmi"];
var keys = JsonConvert.DeserializeObject<Dictionary<string, object>>(fmi.ToString());

This can be solved accurately with this method, just keep in mind, you will need Newtonsoft.Json;
//using Newtonsoft.Json;
// using System.IO;
string dataPath = #"myfile.json"; // Location of the json
string jsonData = "";
using (StreamReader r = new StreamReader(Path.Combine(dataPath)))
{
string json = r.ReadToEnd();
jsonData = json;
}
dynamic obj = JsonConvert.DeserializeObject(jsonData);
string value = obj["name"]; // here name is the object name holding the required data
Console.WriteLine(value);
Console.ReadLine();
/*
* OUTPUT
* itzplayz
*/
Here's the JSON Example
{
"name": "itzplayz"
}
Now you can get the value of the JSON object in the string called value

Related

merging two json result into one and adding the Key inside array?

I've merged two JSON response into a single object:
This is how I did it
string peter= "\"peter\"";
string james= "\"james\"";
var jsonStringJames = await jsonStringJames .Content.ReadAsStringAsync();
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
return Ok("{" + peter+ ":" + jsonStringPeter + ","+ james+ ":" + jsonStringJames + "}");
my JSON looks as follow:
{
"peter": {
"total": 1,
"result": [
{
"value": "James Bond",
"OWNER":"peter" <--- add this
}
]
},
"james": {
"count": 2,
"next": null,
"previous": null,
"results": [{
"gender": "male"
"OWNER":"james" <--- add this
}]
}
}
How do I add the object name as a key? server-side?
Thanks alot!
try this using ´JObject´
var jsonStringPeter = await responsePeter.Content.ReadAsStringAsync();
var objJson = JObject.Parse(jsonStringPeter);
objJson["result"][0]["OWNER"] = "peter";
var jsonStringJames = await jsonStringJames.Content.ReadAsStringAsync();
var objJson2 = JObject.Parse(jsonStringJames);
objJson2["OWNER"] = "james";

Convert Json to explicit new object, List initialization c#

Hi I am wondering if there is a way to convert a json object to explicit new object/List object for instance :
Convert this :
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
into this c# code text:
new className() {
Name = "John",
Age = 30,
Cars = new List (){"Ford", "BMW", "Fiat" }
};
What I want to do is create the equivalent of a json code in to c# code.
You can use the JObject from Newtonsoft library
This is an example from the library
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
Output
{
"CPU": "Intel",
"Drives": [
"DVD read/writer",
"500 gigabyte hard drive"
]
}
Or you can use jsonutils to create a C# equivalence class
And then use Newtonsoft to parse the Json object
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonContent);
You can use online services like https://www.jsonutils.com/
or
function Convert(jsonStr, classNr) {
var i = classNr == undefined ? 0 : classNr;
var str = "";
var json = JSON.parse(jsonStr);
for (var prop in json) {
if (typeof(json[prop]) === "number") {
if (json[prop] === +json[prop] && json[prop] !== (json[prop] | 0)) {
str += prop + " = " + json[prop] + "M, ";
} else {
str += prop + " = " + json[prop] + ", ";
}
} else if (typeof(json[prop]) === "boolean") {
str += prop + " = " + json[prop] + ", ";
} else if (typeof(json[prop]) === "string") {
str += prop + ' = "' + json[prop] + '", ';
} else if (json[prop] == null || json[prop] == undefined) {
str += prop + ' = null, ';
} else if (typeof(json[prop]) === "object") {
str += prop + " = " + Convert(JSON.stringify(json[prop]), i++) + ", ";
}
}
if (str.endsWith(', ')) {
str = str.substring(0, str.length - 2);
}
return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="tin" cols="100" rows="6">
{"A":12}
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').text(Convert($('#tin').val()));" />
<div id="result"></div>
from https://stackoverflow.com/a/34590681/1932159

Delete JSON Data inside Property based on ID in C#

I have a requirement to delete the data inside JSON file. I have tried so many way but it is not deleting the data. I have also tried this example.
Remove JSON objects from a large file
But in above example they are passing a jsonstring but I have a jobject type of data.
My JSON File is as following.
{
"id": 123,
"name": "Pankaj Kumar",
"address": {
"street": "El Camino Real",
"city": "San Jose",
"zipcode": 95014
},
"experiences": [
{
"companyid": 1,
"companyname": "abc1"
},
{
"companyid": 20,
"companyname": "Genpact Headstrong"
},
{
"companyid": 71,
"companyname": "new company"
},
{
"companyid": 77,
"companyname": "Mind Tree LTD"
},
{
"companyid": 89,
"companyname": "TCS"
},
{
"companyid": 22,
"companyname": "Hello World LTD"
}
],
"phoneNumber": 9988664422,
"role": "Developer"
}
I want to delete company based on companyid.
I have tried following code to delete based on company id.
private void DeleteCompany() {
var json = File.ReadAllText(jsonFile);
try {
var jObject = JObject.Parse(json);
JArray experiencesArrary = (JArray) jObject["experiences"];
Console.Write("Enter Company ID to Delete Company : ");
var companyId = Convert.ToInt32(Console.ReadLine());
if (companyId > 0) {
var companyName = string.Empty;
foreach(var company in experiencesArrary.Where(obj => obj["companyid"].Value < int > () == companyId)) {
companyName = Convert.ToString(company["companyname"]);
}
var companyToDeleted = "{ 'id': " + companyId + ", 'companyname': '" + companyName + "'}";
experiencesArrary.Remove(companyToDeleted);
jObject["experiences"] = experiencesArrary;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(jsonFile, output);
} else {
Console.Write("Invalid Company ID, Try Again!");
UpdateCompany();
}
} catch (Exception) {
throw;
}
}
Please suggest or modify my code which delete the data.
There is no need for creating deleteObject like you are doing, you are very close to solution.You can simply find your object like this and remove.
var companyToDeleted = experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId).ToList();
foreach (var item in companyToDeleted)
{
experiencesArrary.Remove(item);
}
Update
var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);
experiencesArrary.Remove(companyToDeleted);

Looping through multiple JObject levels and gathering information as a string

I'm using the following code to gather Json data from a URL.
var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6");
JObject jo = JObject.Parse(json);
JObject ja = (JObject)jo["rgDescriptions"];
int cCount = 0;
int bCount = 0;
int eCount = 0;
foreach(var x in ja){
// I'm stuck here.
string type = (Object)x["type"];
}
CUAI.sendMessage("I found: " + ja.Count.ToString());
Everything is working well until I get to the foreach statement.
Here is a snippet of the JSON Data.
{
"success": true,
"rgInventory": {
"Blah other stuff"
},
"rgDescriptions": {
"637390365_0": {
"appid": "753",
"background_color": "",
"type": "0RBITALIS Trading Card"
"175240190_0": {
"appid": "753",
"background_color": "",
"type": "Awesomenauts Trading Card"
},
"195930139_0": {
"appid": "753",
"background_color": "",
"type": "CONSORTIUM Emoticon"
}
}
}
I'm wanting to loop through each item in rgDescriptions and get the type data as a string, Then check if it contains either background, emoticon or trading card.
I know I can use the if(type.Contains("background")) to check what the item type is, But I'm having trouble with the foreach loop.
If I use foreach(JObject x in ja) I get a cannot convert type Error.
If I use foreach(Object x in ja) It comes up with a Cannot apply indexing of type object.
This error also happens when I use foreach(var x in ja) and string type = (JObject)x["type"];
Can anyone tell me what I'm doing wrong, Please?
You have some errors in your JSON. Check it with jsonlint.com. I think it should look something like this:
{
"success": true,
"rgInventory": {
"Blah other stuff": ""
},
"rgDescriptions": {
"637390365_0": {
"appid": "753",
"background_color": "",
"type": "0RBITALIS Trading Card"
},
"175240190_0": {
"appid": "753",
"background_color": "",
"type": "Awesomenauts Trading Card"
},
"195930139_0": {
"appid": "753",
"background_color": "",
"type": "CONSORTIUM Emoticon"
}
}
}
You can use the JProperty, JToken and the SelectToken Method to get the type:
var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6");
JObject jo = JObject.Parse(json);
foreach (JProperty x in jo.SelectToken("rgDescriptions"))
{
JToken type = x.Value.SelectToken("type");
string typeStr = type.ToString().ToLower();
if (typeStr.Contains("background"))
{
Console.WriteLine("Contains 'background'");
}
if (typeStr.Contains("emoticon"))
{
Console.WriteLine("Contains 'emoticon'");
}
if (typeStr.Contains("trading card"))
{
Console.WriteLine("Contains 'trading card'");
}
}

How to write all keys and values within Dictionary<string, object> to a text file?

I have a Dictionary<string, object> advertiserResponse that looks like this...
"AdvertiserLookup": {
"Agency": {
"AgencyAlpha": "ABC",
"Media": [
{
"Code": "123",
"Name": "XYZ",
"Advertisers": {
"Advertiser": [
{
"Code": "JKL",
"Name": "EFG",
"BusinessKey": "HIJ"
},
{
"Code": "KLM",
"Name": "NOP",
"BusinessKey": "QRS"
},
{
This is the line I'm using to try to write to a text file:
File.WriteAllLines("test.txt", advertiserResponse.Select(x => "[" + x.Key + " " + x.Value + "]").ToArray());
I'm expecting the Json (not necessary in pretty print) with all keys and text below AdvertiserLookup.
What I get in test.txt:
[AdvertiserLookup System.Collections.Generic.Dictionary``2[System.String,System.Object]]
How do I write the entire thing to text?
Give Json.NET a try. You should be able to serialize your dictionary.
var jsonString = JsonConvert.SerializeObject(advertiserResponse, Formatting.Indented)

Categories

Resources