Json formation for sending it to function - c#

i want to pass following json as an reference in my console application in c#
{"val1":["dfgdsfgdfgsdf"],"val2":258915,"val3":"PPaaaA","val4":null,
"valJSON":"[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"}
I am doing following , but it is not working
JsonSerializer serializer = new JsonSerializer();
dynamic item = serializer.Deserialize<object>("
{"val1":["dfgdsfgdfgsdf"],"val2":258915,"val3":"PPaaaA","val4":null,
"valJSON":"[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"}
");
any other way i can pass this to function ?
to simplyfy
when i try to assign this to string it gives error can anyon hlp me

You should remove object type from function call:
JsonSerializer serializer = new JsonSerializer();
dynamic item = serializer.Deserialize("...");

I would use Newtonsoft's solution, if it's possible, i never regreted.
In your case, i'd use:
string json = #"{
"val1": [
"dfgdsfgdfgsdf"
],
"val2": 258915,
"val3": "PPaaaA",
"val4": null,
"valJSON": "[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"
}"
dynamic rss = JObject.Parse(json);
And then accessing values from it like:
var val2 = rss.val2;
I'm not sure if that's what you was looking for, but i tried...
Read more: http://www.newtonsoft.com/json/help/html/QueryJson.htm
Then, if you want more how to "install" newtonsoft: How to install JSON.NET using NuGet?

If you want to parse Json to the exact class you can try this
RootObject item = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(#"D:\file.txt"));
public class RootObject
{
public List<string> val1 { get; set; }
public int val2 { get; set; }
public string val3 { get; set; }
public object val4 { get; set; }
public string valJSON { get; set; }
}

Related

System.Text.Json.deserialize Json String

I have a question about System.Text.Json.deserialize.
I have got the Json value like this
{
"id" :"1",
"ShopName" :"Paint Shop",
"Books" : [1,2]
}
It can easy convert to simple object as
public class bookstore {
public int id {get;set}
public string ShopName {get;set}
public IEnumerable<int> Books {get;set}
}
But I have a function which convert books array int into list of object like this
{
"id" :"1",
"ShopName" :"Paint Shop",
"Books" : [
{
"bookId":1,
"bookName":"Peter Pan",
"location":"A01"
},
{
"bookId":2,
"bookName":"Cooking Book",
"location":"A02"
}
]
}
Right now, I want to modify the value of Books[1].location value, by using jsonnode.parse(string) to convert the object.
Can I know how to do it ?
Thank you
Don't know why you want to use the JsonNode.Parse().
If you just want to modify the location's value, maybe you can use the JsonSerializer with BookStore and Book class to help you.
📌 The Book class is a IEnumerable property of BookStore.
an example by .NET6 Console App
📌 BookClass is a 2-level nested class
// See https://aka.ms/new-console-template for more information
using System.Text.Json;
// Initialize json string
string jsonStr = "{\"id\": 1, \"ShopName\" :\"Paint Shop\", \"Books\" : [\r\n {\r\n \"bookId\":1,\r\n \"bookName\":\"Peter Pan\",\r\n \"location\":\"A01\"\r\n },\r\n {\r\n \"bookId\":2,\r\n \"bookName\":\"Cooking Book\",\r\n \"location\":\"A02\"\r\n }\r\n ]\r\n }";
// Deserilize to object
Bookstore bookstore = JsonSerializer.Deserialize<Bookstore>(jsonStr);
// Write the location's value
Console.WriteLine(bookstore.Books.ToArray()[1].location);
// Modified the location's value
bookstore.Books.ToArray()[1].location += "_Modified";
// Write the modified location's value
Console.WriteLine(bookstore.Books.ToArray()[1].location);
// See result output
Console.ReadLine();
public class Bookstore
{
public int id { get; set; }
public string ShopName { get; set; }
public IEnumerable<Book> Books { get; set; }
}
public class Book
{
public int bookId { get; set; }
public string bookName { get; set; }
public string location { get; set; }
}
Result output image
If you persist to use JsonNode.Parse(), then need more steps. like this.
// See https://aka.ms/new-console-template for more information
using System.Text.Json;
using System.Text.Json.Nodes;
// Initialize json string
string jsonStr = "{\"id\": 1, \"ShopName\" :\"Paint Shop\", \"Books\" : [\r\n {\r\n \"bookId\":1,\r\n \"bookName\":\"Peter Pan\",\r\n \"location\":\"A01\"\r\n },\r\n {\r\n \"bookId\":2,\r\n \"bookName\":\"Cooking Book\",\r\n \"location\":\"A02\"\r\n }\r\n ]\r\n }";
// Parse to jsonNode
JsonNode jsonNode = JsonNode.Parse(jsonStr);
// Convert to JsonObject
JsonObject jsonObject = jsonNode.AsObject();
// Convert Books to Json Array
JsonArray jsonArray = jsonObject["Books"].AsArray();
// Convert index 1 in array to Json object
JsonObject book1Object = jsonArray[1].AsObject();
// Write the location value
Console.WriteLine(book1Object["location"]);
// Modify location value
book1Object["location"] += "_modified";
// Write the modified location value
Console.WriteLine(book1Object["location"]);
// See output
Console.ReadLine();
public class Bookstore
{
public int id { get; set; }
public string ShopName { get; set; }
public IEnumerable<Book> Books { get; set; }
}
public class Book
{
public int bookId { get; set; }
public string bookName { get; set; }
public string location { get; set; }
}
Other suggestion
Use Newtonsoft.Json is better. Because when convert a json to a C# object, will need to convert many properties with different value type.
The Newtonsoft.Json had already handle these situation, at the mean time the System.Text.Json does not.
You can use JObject to modify json directly
var jObject = JObject.Parse(json);
jObject["Books"][1]["location"] = "new value";
Result:
Note:
You should add Newtonsoft.Json package.
Since you are using System.Text.Json, you can change value using this code
var jsonParsed=JsonNode.Parse(json);
jsonParsed["Books"][1]["location"]="A03";
after this , if you need you can get an updated json
json = System.Text.Json.JsonSerializer.Serialize(jsonParsed, new JsonSerializerOptions {WriteIndented=true});

How to Deserialize Json Object - C#

A web service returns JSON object as blew:
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}"
I tried to Deserialize by doing this:
Define the objects
public class RootResponseClass
{
public ResponseParametersClass[] d { get; set; }
}
public class ResponseParametersClass
{
public string sname { get; set; }
public string region { get; set; }
public string name { get; set; }
}
Write the Deserialize Method
JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);
But It is gives error "Cannot convert object of type 'System.String' to type 'NAS.Helpers.ResponseParametersClass[]", So how can i do it!
Solution
public class RootResponseClass
{
public string d { get; set; }
}
And for deserialize method :
JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);
List<ResponseParametersClass> obj2 = new List<ResponseParametersClass>();
obj2 = ser2.Deserialize<List<ResponseParametersClass>>(obj.d.ToString());
You can use the package using Newtonsoft.Json; for deserializing JSON
example
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}";
var foo = JsonConvert.DeserializeObject<RootResponseClass>(JsonString);
foo is your deserialized object.
EDIT
As extra information why the initial way is not working is because your array is starting with quotes so its recognized as a string. After the "{"d": should be just [] instead of "[]"
Thanx Dnomyar96 for pointing that extra out.
Your Json string seems to contain another Json string. So in order to deserialize this, you'd need to deserialize as you're doing now, but change the ResponseParametersClass to string.
Then you'd need to deserialize the string you just got (as a List<ResponseParametersClass>). So in this case you'd need to deserialize in two seperate steps.

Convert typenameHandling json to regular json

Is it possible to convert json produced by JSON.NET with type name handling set on into regular json?
My application cannot assume anything about the types it is receiving as it will be 1 of many 1000s of classes. I just need to remove the type information from the json.
For example I receive this json string in my application:
{
"$type": "MyAssembly.MyType, MyAssembly",
"$id": 1,
"MyValue": 5
}
Can I convert it into this json:
{
"MyValue": 5
}
I've tried loading the original json into JObject and then removing all members starting with $ but then found this fails when working with arrays, as they can look like this:
{
"MyArray": {
"$type": "System.Collections.List, System",
"$values": [
{
"$type": "MyAssembly.MyType, MyAssembly",
"MyValue": 5
}
]
}
}
Is there anything built into JSON.NET that allows such a conversion to take place?
Here is an example to show what I mean
class Program
{
static void Main(string[] args)
{
JsonSerializerSettings withNamehandling = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.All,
Formatting = Formatting.Indented
};
var obj = new MyObj();
//This is the json which my application will be receiving. My application does not know about MyObj or MyType.
var json = JsonConvert.SerializeObject(obj, withNamehandling);
Console.WriteLine(json);
//Deserialize the object without namehandling enabled
var deserializeObject = JsonConvert.DeserializeObject(json);
//Serialize again without namehandling enabled
var json2 = JsonConvert.SerializeObject(deserializeObject, Formatting.Indented);
//Metadata removed from root node but not children.
Console.WriteLine(json2);
Console.ReadLine();
}
}
class MyObj
{
public List<MyType> Types { get; set; } = new List<MyType>()
{
new MyType()
{
Value = 5
}
};
}
class MyType
{
public int Value { get; set; }
}
If I use http://json2csharp.com/, below structure I get
public class RootObject
{
public string __invalid_name__$type { get; set; }
public int __invalid_name__$id { get; set; }
public int MyValue { get; set; }
}
With that what if you create your model as
public class MyType
{
public int MyValue { get; set; }
}
And then deserialize it to that type MyType
You can as well use JsonProperty annotation and make the specific property not required like
public class RootObject
{
[JsonProperty(Required = Required.Default)]
public string __invalid_name__$type { get; set; }
[JsonProperty(Required = Required.Default)]
public int __invalid_name__$id { get; set; }
public int MyValue { get; set; }
}
Yes, you can deserialize the data and then reserialize it. By default JSON .NET will not include the type names, so that must be set by the serialization side with a purpose, to use the same assembly to serialize/deserialize the data, so be careful when manipulating that data without the real source assembly.
Anyway, to deserialize the data first create a model which fits with the real data:
public class RootObject
{
public List<MyObject> MyArray { get; set; }
}
public class MyObject
{
public MyType MyValue { get; set; }
}
//I assume this because there's not info about "MyType"
public class MyType : String { }
Now you create a JsonSerializerSettings and set the TypeNameHandling to None:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };
And deserialize the data to your struct:
var deser = JsonConvert.DeserializeObject<RootObject>(seria, settings);
Now you have the data reconstructed and you can reserialize it with no type handling and it will remove all the namespaces and class types:
var cleanJson = JsonConvert.SerializeObject(deser, settings);
EDIT:
IF you don't need to reconstruct the structure just use the settings as posted and de/serialize to JObject:
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };
var deser = JsonConvert.DeserializeObject(SourceData, settings);
var clean = JsonConvert.SerializeObject(deser, settings);

Easiest way to parse JSON response

Is there any easy way to parse below JSOn in c#
{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}
and in case Multiple results.
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.)
You can safely use built-in JavaScriptSerializer without referencing additional third party libraries:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);
I found a way to get it without using any external API
using (var w = new WebClient())
{
var json_data = string.Empty;
string url = "YOUR URL";
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var result = jsSerializer.DeserializeObject(json_data);
Dictionary<string, object> obj2 = new Dictionary<string, object>();
obj2=(Dictionary<string,object>)(result);
string val=obj2["KEYNAME"].ToString();
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
}
For me ... the easiest way to do that is using JSON.net do a deserialize to a entity that represents the object, for example:
public class Message
{
public string status { get; set; }
public string messageid { get; set; }
public string gsm { get; set; }
}
public class YourRootEntity
{
public string type { get; set; }
public string totalprice { get; set; }
public string totalgsm { get; set; }
public string remaincredit { get; set; }
public List<Message> messages { get; set; }
}
And do this:
YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);

Parsing JSON data in C#

I have a JSON data as follows
{"id": "367501354973","from": {
"name": "Bret Taylor",
"id": "220439" }
which is returned by an object(result) of IDictionary[String, Object]
In my C# code:
I have made a class for storing the JSON value which is as follows
public class SContent
{
public string id { get; set; }
public string from_name { get; set; }
public string from_id { get; set; }
}
My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:
List<object> data = (List<object>)result["data"];
foreach (IDictionary<string, object> content in data)
{
SContent s = new SContent();
s.id = (string)content["id"];
s.from_name = (string)content["from.name"];
s.from_id = (string)content["from.id"];
}
When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"
When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.
I think i am not able to refer the nested JSON data properly.
Can anyone just validate it and please tell me how to refer nested data in JSON in C#?
Thanks
I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?
You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)
Using that class, you would write your code like this:
public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}
public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}
Then deserialization looks like this:
var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);
See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Categories