Convert string to json using C# - c#

i am beginner to C#, i have a very long string and want to convert it to json, string is
{"employees":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
\
any ideas?

You can do something like this:
var jobject = JsonConvert.DeserializeObject<JObject>(yourVariable);
this is using Newtonsoft's json library that you can get from nuget.
Also JObject is the C# equivalent to a JSON object so that's probably something you'll want to use.

u an also use,
JObject.Parse(urJsonString);
JObject is in Newtonsoft.Json.Linq namespace.

You need to Deserialize your string as follows :
// Your string here
string str = #"[{"categories":
[{"id":0,"level":0,"label":"Product Names","subitems":
[{"id":0,"level":1,"label":"Soren","subitemslevel3":
[{"id":0,"level":2,"label":"AAAA"},{"id":0,"level":2,"label":"bbb"}]},
{"id":0,"level":1,"label":"Test","subitemslevel3":
[{"id":0,"level":2,"label":"111"},{"id":0,"level":2,"label":"2222"}]}]},
{"id":0,"level":0,"label":"Product texts","subitems":
[{"id":0,"level":1,"label":""},{"id":0,"level":1,"label":"<p>Disney <strong>Princess<\/strong><\/p>\n"},{"id":0,"level":1,"label":"<p>Machines & Mechanisms - <strong>Middle<\/strong><\/p>\n"},{"id":0,"level":1,"label":"64738574"},{"id":0,"level":1,"label":"8765432"},{"id":0,"level":1,"label":"a"},{"id":0,"level":1,"label":"aa"},{"id":0,"level":1,"label":"ab"},{"id":0,"level":1,"label":"abe"},{"id":0,"level":1,"label":"aD!?"},{"id":0,"level":1,"label":"Bionicle"},{"id":0,"level":1,"label":"Disney Princess"},{"id":0,"level":1,"label":"er"},{"id":0,"level":1,"label":"foo foo"},{"id":0,"level":1,"label":"hej"},{"id":0,"level":1,"label":"igen"},{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"metadata"},{"id":0,"level":1,"label":"metadata from kafka"},{"id":0,"level":1,"label":"Metatest"},{"id":0,"level":1,"label":"q"},{"id":0,"level":1,"label":"Simpsons"},{"id":0,"level":1,"label":"test"},{"id":0,"level":1,"label":"Test 123"},{"id":0,"level":1,"label":"Test Metadata 123"}]},{"id":0,"level":0,"label" :"Specialist Terms","subitems":[{"id":0,"level":1,"label":"meta"},{"id":0,"level":1,"label":"new category 1111"},{"id":0,"level":1,"label":"secret category"}]}]}]";
// DeSerialize your object
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Related

How to deserialize an object that i dont know

Normally I'm using Newtonsoft to deserialize like this
List<myObject> deserializeObj = JsonConvert.DeserializeObject<List<myObject>>(mysample);
But now, i'm facing a problem where the attribute of mysample can be dynamic which is user define themselves. Thus i cannot use myObject anymore as it is fixed class. So how can i deserialize object like that?
For example the mysample can be something like bellow and etc:
[{"Name":"a","Phone":"a","Ic":"a"},{"Name":"b","Phone":"b","Ic":"b"}]
OR
[{"Id":"a"},{"Id":"b"}]
Target Framework is .NET Framework 3.5
you can use Dynamic Type
List<dynamic> deserializeObj = JsonConvert.DeserializeObject<List<dynamic>>(mysample);
.NET Framework 3.5 :
List<object> deserializeObj = JsonConvert.DeserializeObject<List<object>>(mysample);
well you can then use reflection to access value
sample:
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
dotnt forget to add using System.Reflection;
To avoid using dynamic, you can parse the json using JArray
JArray array = JArray.Parse(json);
Thus i cannot use myObject anymore as it is fixed class. So how can i deserialize object like that?
To get rid from this problem Newtonsoft.Json have very well feature that we can use
If you don't know which json object or array comes from your resource. means you can't determine its c# respective object then newtonsoft have JObject and JArray can handle this problem like
1) Suppose your json string is object like
var json = #"{ 'Name':'a','Phone':'a','Ic':'a'}";
Then you can use JObject here
JObject jObject = JsonConvert.DeserializeObject<JObject>(json);
2) Suppose your json string is array like
var json1 = #"[{ 'Name':'a','Phone':'a','Ic':'a'},{ 'Name':'b','Phone':'b','Ic':'b'}]";
Then you can use JArray here
JArray jArray = JsonConvert.DeserializeObject<JArray>(json1);
After successfully getting JArray from your json string. you can also querying on your deserialized object to get particular object from it like
JObject jObject1 = jArray.Children<JObject>().FirstOrDefault();
JObject jObject2 = jArray.Children<JObject>().FirstOrDefault(x => x["Name"] != null && x["Name"].ToString() == "a");
int count = jArray.Children<JObject>().Count();
If you want to get certain key:value pair from your json then you can get it by below code
JProperty jProperty = jObject1.Properties().Where(x => x.Name == "Name").FirstOrDefault();
var value = (string)jProperty.Value;
Try once may it help you.

How to modify a deserialized object

I have a JSON string as follows
string str = "{"Id":["1799"],"Type":1,"Date":null,"Group":null,"Ids":1799}";
I want to covert it to the following format
{"Id":1799,"Type":1,"Date":null,"Group":null }
In short I want to remove the "Ids" and convert "Id" value to string.
For this I tried deserializing this string as follows-
object yourOjbect = new JavaScriptSerializer().DeserializeObject(str);
But here I am stuck. How Can I remove/change a value from this object.
I tried converting this object to array and list but could not find remove/modify option in it.
Maybe you can use the JSON framework for .NET from http://www.newtonsoft.com/json (also available as a nuget package)
Then you can use the following to Deserialize into your object
string str = "{"Id":["1799"],"Type":1,"Date":null,"Group":null,"Ids":1799}";
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);
Then maybe create a different object for your output, and have a constructor that will accept the original object as input, and then serialise it to Json. The constructor must then do any internal conversions/changes that you require.
OtherObject other = new OtherObject(myObj); //Create new object from original.
string json = JsonConvert.SerializeObject(other);
Expando Object.
string str = "{"Id":["1799"],"Type":1,"Date":null,"Group":null,"Ids":1799}";
Initially, deserialize the json using NewtonJson lib
dynamic parsedJson = JsonConvert.DeserializeObject<dynamic>(str);
Dynamic newStr = new ExpandoObject();
newStr.Id = parsedJson.Id.ToString();
newStr.Type = parsedJson.Type;
...
then serilize the newStr:
str newJson = JsonConvert.SerializeObject(newStr);
Output :
{"Id":1799,"Type":1,"Date":null,"Group":null }

Deserialize JSON with json.NET into C# dynamic

I have following problem: I have a json file that looks like this
{
"Path": {
"FirstPath": "/1/2/text()"
}
}
If I parse this JSON-File with Newtonsoft like this
dynamic dyn = JObject.Parse(json);
or this
dynamic dyn = JsonConvert.DeserializeObject(json);
I get a dynamic object that needs to be used like this
dyn.Path.FirstPath.Value
How can I get rid of the Value stuff? All of my objects in the JSON end up being a string. I don't want to always write ".Value" at the end if it is not necessary.
I tested this using Newtonsoft 8.0.2 and it works fine.
dynamic dyn = JObject.Parse(json);
string value = dyn.Path.FirstPath;
Value should equal /1/2/text().

Convert Struct to JSON

I have a struct, I want to convert it to JSON and save it as local file.
I couldn't find any source that explain how to convert a C# struct into a JSON.
I am using a console application for that, not a webservice/web, etc.
JavaScriptSerializer Class
var serializer = new JavaScriptSerializer();
YourStruct myStruct = new YourStruct(x,y,z);
var json = serializer.Serialize(myStruct);
JSON.NET
The other alternative JSON.net, it do not depends on System.Web.* assemblies:
YourStruct myStruct = new YourStruct(x,y,z);
var json = JsonConvert.SerializeObject(myStruct);
I would recommend using JSon.net. You can then do something like:
string json = JsonConvert.SerializeObject(myObj); // myObj is the struct you want to serialize
File.WriteAllText("Foo.json", json); //Write the text to Foo.json
Install https://www.nuget.org/packages/Newtonsoft.Json/
Use JsonConvert.SerializeObject(structName) to serialize object. Do not forget to change argument name to yours

Deserializing variable Type JSON array using DataContractJsonSerializer

I have a JSON string in this form:
string jsonStr = "[\"A\", [\"Martini\", \"alovell\"],[\"Martin\", \"lovell\"]]"
I am trying to deserialize the JSON using the C# .NET deserializer DataContractJsonSerializer with the following code snippet
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof<X>);
X data = (X)serializer.ReadObject(ms);
Now since the JSON array is an array of variable types I do not know what type of object
X should be
If my String were
jsonStr = "[[\"Martini\", \"alovell\"],[\"Martin\", \"lovell\"]]"
I could use this:
X = List<List<String>>
and that would work for me. I was wondering if there is any way to deserialize variable type JSON array?
You could use Json.NET to do this.
JArray a = JArray.Parse(jsonStr);
The JArray would contain either strings or nested JArray's depending on the JSON.

Categories

Resources