I have a List that I would like to convert to JSON using C# and Newtonsoft.
tags
[0]: "foo"
[1]: "bar"
Output to be:-
{"tags": ["foo", "bar"]}
Can anybody point me in the right direction please? I can convert the List to JSON okay but they key thing here is I need the "tags" part in the JSON which I do not get with a convert using JsonConvert.SerializeObject(tags).
The below code wraps the list in an anonymous type, and thus generates what you are looking for.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var list = new List<string> {"foo", "bar"};
var tags = new {tags = list};
Console.WriteLine(JsonConvert.SerializeObject(tags));
Console.ReadLine();
}
}
}
Arguably the easiest way to do this is to just write a wrapper object with your List<string> property
public class Wrapper
{
[JsonProperty("tags")]
public List<string> Tags {get; set; }
}
And then when serialized this gives the output you expect.
var obj = new Wrapper(){ Tags = new List<string>(){ "foo", "bar"} };
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
// outputs: {"tags":["foo","bar"]}
Live example: http://rextester.com/FTFIBT36362
Use like this.
var data = new { tags = new List<string> { "foo", "bar" } };
var str = Newtonsoft.Json.JsonConvert.SerializeObject(data);
Output:
{"tags": ["foo","bar"] }
Hope this helps.
Create a separate class like this:
public class TagList
{
[JsonProperty("tags")]
List<string> Tags { get; set; }
public TagList(params string[] tags)
{
Tags = tags.ToList();
}
}
Then call:
JsonConvert.SerializeObject(new TagList("Foo", "Bar"));
You can use anonymous object to wrap your list like that:
JsonConvert.SerializeObject(new {Tags = tags});
You could use this.
static void Main(string[] args)
{
List<string> messages = new List<string>();
messages.Add("test");
messages.Add("test 2");
Items data = new Items { items = messages };
string output = JsonConvert.SerializeObject(data);
JObject jo = JObject.Parse(output);
Console.WriteLine(jo);
}
public class Items
{
public List<string> items { get; set; }
}
Produces:
{
"items": [
"test",
"test 2"
]
}
Related
"title" : { "newTitle" : "Test"}
"tags" : { "newTags" : ["Tag1", "Tag2"] }
Newtonsoft.Json.Linq;
var json = JObject.Parse(json: json);
var title; // "Test2" in title
List<string> tags; // "TagA", "TagB", "TagC" in tags
json["title"]["newTitle"] = title; // works well
json["tags"]["newTags"] = tags; // not work
I want the JSON result as below:
"title" : { "newTitle" : "Test2"}
"tags" : { "newTags" : ["TagA", "TagB", "TagC"] }
I want to modify some values of JSON. int or string worked well. However, the List or Array does not work.
Please give me a good opinion.
I used a translator. So the writing may be awkward.
Assume your JSON data has defined object template, you can create a class based on your JSON data. With Newtonsoft.Json, you deserialize your JSON into an object and next update the object's properties value.
Note: When access object's inner properties for example Title.NewTitle and Tags.NewTags, you may need to add some null checking for preventing NullReferenceException.
1st solution: Convert to strongly-typed object
public static void Main()
{
var json = "{\"title\" : { \"newTitle\" : \"Test\"}, \"tags\" : { \"newTags\" : [\"Tag1\", \"Tag2\"] }}";
var inputObj = JsonConvert.DeserializeObject<JsonInput>(json);
inputObj.Title.NewTitle = "Test2";
inputObj.Tags.NewTags = new List<string> {"TagA", "TagB", "TagC"};
Console.WriteLine(JsonConvert.SerializeObject(inputObj));
}
public class JsonInput
{
public Title Title {get;set;}
public Tags Tags {get;set;}
}
public class Title
{
public string NewTitle {get;set;}
}
public class Tags
{
public List<string> NewTags {get;set;}
}
1st solution Code snippets and Output
2nd solution: With dynamic
To update array, you need parse your List<string> to JArray type
public static void Main()
{
var json = "{\"title\" : { \"newTitle\" : \"Test\"}, \"tags\" : { \"newTags\" : [\"Tag1\", \"Tag2\"] }}";
var title = "Test2"; // "Test2" in title
List<string> tags = new List<string> {"TagA", "TagB", "TagC"}; // "TagA", "TagB", "TagC" in tags
dynamic root = JObject.Parse(json);
JObject titleObj = (JObject)root["title"];
titleObj["newTitle"] = title;
JObject tagsObj = (JObject)root["tags"];
tagsObj["newTags"] = JArray.FromObject(tags);
Console.WriteLine(root);
}
2nd solution Code snippets and Output
try this
var jsonObject=JObject.Parse(json);
var newTitle = "Test2";
List<string> newTags = new List<string> { "TagA", "TagB", "TagC"};
jsonObject["title"]["newTitle"]= newTitle;
jsonObject["tags"]["newTags"]= JArray.FromObject(newTags);
result
{
"title": {
"newTitle": "Test2"
},
"tags": {
"newTags": [
"TagA",
"TagB",
"TagC"
]
}
}
Let's say I have this example JSON:
"Test": {
"KIf42N7OJIke57Dj6dkh": {
"name": "test 1"
},
"xsQMe4WWMu19qdULspve": {
"name": "test 2"
}
}
I want to parse this into an Array of a custom class I have, which will be exampled below:
class Class1 {
public string Name { get; set; }
Class1(string name) {
Name = name;
}
}
How can I parse this using Json.NET's JObject.Parse?
You can achieve your goal with JPath query like this :
var myArray = JObject
.Parse(json)
.SelectTokens("$.Test..name")
.Values<string>()
.Select(s => new Class1(s))
.ToArray();
But probably not the best way to do it.
I personnaly prefere to create classes to represent the json structure and then apply transformations.
void Main()
{
var json = #"{""Test"": {
""KIf42N7OJIke57Dj6dkh"": {
""name"": ""test 1""
},
""xsQMe4WWMu19qdULspve"": {
""name"": ""test 2""
}
}
}";
var root = JsonConvert.DeserializeObject<Root>(json);
var array = root.Test.Select(i => i.Value).ToArray();
array.Dump();
}
public class Root
{
public Dictionary<string, Class1> Test { get; set; }
}
public class Class1
{
public string Name { get; set; }
public Class1(string name)
{
Name = name;
}
}
To begin with, your Json is missing starting/closing braces. The Json needs to have wrapping braces around the Test value.
{
'Test':
{
'KIf42N7OJIke57Dj6dkh': {'name': 'test 1'},
'xsQMe4WWMu19qdULspve': {'name': 'test 2'}
}
}
If you are missing it in the original Json, you could wrap the current input Json as following.
var correctedJson = $"{{{inputJsonString}}}";
If you want to parse the Json Objects to Array of Class1 without creating additional concrete data structures and using JPath Queries, you could use Anonymous Types for the purpose using the DeserializeAnonymousType Method proved by Json.Net. For example,
var sampleObject = new {Test = new Dictionary<string,Class1>()};
var data = JsonConvert.DeserializeAnonymousType(correctedJson,sampleObject);
var result = data.Test.Select(x=>x.Value).ToArray();
You could also achieve it using JPath Query or creating Concrete Data Structures as #Kalten as described in his answer.
How do I Deserialize the following. The problem is that the variable name is a number. So how should MyClass be defined?
json_str:
{"23521952": {"b": [], "o": []}, "23521953": {"b": [], "o": []}}
class MyClass { //? };
var var = JsonConvert.DeserializeObject<MyClass>(json_str);
This sounds like the outer object is actually a dictionary:
using System.Collections.Generic;
using Newtonsoft.Json;
class Foo
{
// no clue what b+o look like from the question; modify to suit
public int[] b { get; set; }
public string[] o { get; set; }
}
static class P
{
static void Main()
{
var json = #"{""23521952"": {""b"": [], ""o"": []}, ""23521953"": {""b"": [], ""o"": []}}";
var obj = JsonConvert.DeserializeObject<Dictionary<string, Foo>>(json);
foreach(var pair in obj)
{
System.Console.WriteLine($"{pair.Key}, {pair.Value}");
}
}
}
You can use anonymous type deserialization for your data like this, without creating classes for properties of JSON. Hope it works.
var finalResult=JsonConvert.DeserializeAnonymousType(
json_str, // input
new
{
Id=
{
new
{
b=new[], o=new[]
}
}
}
);
foreach(var id in finalResult.Id)
{
console.write(id); // gives ids like 23521952
console.write(id.b[0]) // gives first elemnt in 'b' array
}
My code for the object is as follows,
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<object> modified_listofstrings = new List<object>();
List<string> p_Name = new List<string>();
List<float> Data = new List<float>();
List<string> s_Name = new List<string>();
List<float> p_Value = new List<float>();
var obj1=new{
Data=p_Value
};
var obj2 = new
{
Series=obj1,
};
modified_listofstrings.Add(obj1);
jSearializer.Serialize(modified_listofstrings);
and output I get is as below,
[{"Series":{"Data":[14,14,14,14,18,18,18,18,17,15,13,12]}}]
but I want output as in below format,
"Series" : [ { "Data" : [14,14,14,14,18,18,18,18,17,15,13,12,""] } ],
since I want to use the Values as series.Data... any help will be greatly appreciated,
modified_listofstrings has List type, so it always has been serialized as array. But you may serialize only first element of modified_listofstrings -
jSearializer.Serialize(modified_listofstrings[0]);
and get exactly what you want.
or another answer. just change obj1 property creating like this:
var obj1=new[] {
new { Data = p_Value }
};
Or change obj2 like this:
var obj2 = new
{
Series = new[] { obj1 }
};
Try to have your modified_listofstrings as an object and not a List. Unless you want it to be a list ofcourse. If so do a jSearializer.Serialize(modified_listofstrings[0]) as #Dmytro Rudenko suggested.
Try thinking of json to convert in form of csharp classes..
this will avoid problems
from http://json2csharp.com/
public class Series
{
public List<object> Data { get; set; }
}
public class Root
{
public List<Series> Series { get; set; }
}
now add items to collection and serialize object .. this is right approach when you serialize and deserialize object.
Trying to convert a JSON string into an object in C#. Using a really simple test case:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
The problem is that routes_list never gets set; it's an undefined object. Any ideas?
Or, you can use the Newtownsoft.Json library as follows:
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
Where T is your object type that matches your JSON string.
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
You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.
If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:
var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);
If you want to use the dynamic keyword, you can read how here.
If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:
class MyProgram {
struct MyObj {
public string test { get; set; }
}
static void Main(string[] args) {
var json_serializer = new JavaScriptSerializer();
MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list.test);
Console.WriteLine("Done...");
Console.ReadKey(true);
}
}
Using dynamic object with JavaScriptSerializer.
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
//test Result = "some data"
Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
one line code solution.
var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Jsonstring);
Myclass oMyclass = Newtonsoft.Json.JsonConvert.DeserializeObject<Myclass>(Jsonstring);
You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.
Class for the type of object you receive:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Code:
static void Main(string[] args)
{
string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
User user = JsonConvert.DeserializeObject<User>(json);
Console.ReadKey();
}
this is a very simple way to parse your json.
Here's a simple class I cobbled together from various posts.... It's been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.
The below code can be run in LinqPad to test it out by:
Right clicking on your script tab in LinqPad, and choosing "Query
Properties"
Referencing the "System.Web.Extensions.dll" in "Additional References"
Adding an "Additional Namespace Imports" of
"System.Web.Script.Serialization".
Hope it helps!
void Main()
{
string json = #"
{
'glossary':
{
'title': 'example glossary',
'GlossDiv':
{
'title': 'S',
'GlossList':
{
'GlossEntry':
{
'ID': 'SGML',
'ItemNumber': 2,
'SortAs': 'SGML',
'GlossTerm': 'Standard Generalized Markup Language',
'Acronym': 'SGML',
'Abbrev': 'ISO 8879:1986',
'GlossDef':
{
'para': 'A meta-markup language, used to create markup languages such as DocBook.',
'GlossSeeAlso': ['GML', 'XML']
},
'GlossSee': 'markup'
}
}
}
}
}
";
var d = new JsonDeserializer(json);
d.GetString("glossary.title").Dump();
d.GetString("glossary.GlossDiv.title").Dump();
d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump();
d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump();
d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump();
}
// Define other methods and classes here
public class JsonDeserializer
{
private IDictionary<string, object> jsonData { get; set; }
public JsonDeserializer(string json)
{
var json_serializer = new JavaScriptSerializer();
jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
}
public string GetString(string path)
{
return (string) GetObject(path);
}
public int? GetInt(string path)
{
int? result = null;
object o = GetObject(path);
if (o == null)
{
return result;
}
if (o is string)
{
result = Int32.Parse((string)o);
}
else
{
result = (Int32) o;
}
return result;
}
public object GetObject(string path)
{
object result = null;
var curr = jsonData;
var paths = path.Split('.');
var pathCount = paths.Count();
try
{
for (int i = 0; i < pathCount; i++)
{
var key = paths[i];
if (i == (pathCount - 1))
{
result = curr[key];
}
else
{
curr = (IDictionary<string, object>)curr[key];
}
}
}
catch
{
// Probably means an invalid path (ie object doesn't exist)
}
return result;
}
}
As tripletdad99 said
var result = JsonConvert.DeserializeObject<T>(json);
but if you don't want to create an extra object you can make it with Dictionary instead
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);
add this ddl to reference to your project: System.Web.Extensions.dll
use this namespace: using System.Web.Script.Serialization;
public class IdName
{
public int Id { get; set; }
public string Name { get; set; }
}
string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
Copy your Json and paste at textbox on json2csharp and click on Generate button.
A cs class will be generated use that cs file as below
var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
Where RootObject is the name of the generated cs file;
Another fast and easy way to semi-automate these steps is to:
take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down.
Update the name in the top left to your class name, it defaults to "Welcome".
In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.
app.quicktype.io generated serialize methods based on Newtonsoft.
Alternatively, you can now use code like:
WebClient client = new WebClient();
string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");
var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.
JsonTextReader reader = null;
try
{
WebClient webClient = new WebClient();
JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
reader.SupportMultipleContent = true;
}
catch(Exception)
{}
JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);
First you have to include library like:
using System.Runtime.Serialization.Json;
DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";
using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
BlogSite b = (BlogSite)desc.ReadObject(ms);
Console.WriteLine(b.Name);
Console.WriteLine(b.Description);
}
Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.
public class Student
{
public string FirstName {get;set:}
public string LastName {get;set:}
public int[] Grades {get;set:}
}
public static Student ConvertToStudent(string std)
{
var serializer = new JavaScriptSerializer();
Return serializer.Deserialize<Student>(std);
}
Or, you can use the System.Text.Json library as follows:
using System.Text.Json;
...
var options = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
var result = JsonSerializer.Deserialize<List<T>>(json, options);
Where T is your object type that matches your JSON string.
System.Text.Json is available in:
.NET Core 2.0 and above
.NET Framework 4.6.1 and above