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.
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"
]
}
}
I have this code right here to add a piece of JSON to a file, but instead of working it makes an array with [] breaking how my file is read.
var serverid = ctx.Guild.Id.ToString();
List<data> _data = new List<data>();
_data.Add(new data() {
mute = $"{Role.Name}"
});
string json = JsonConvert.SerializeObject(_data.ToList());
File.WriteAllText(#$".\serverconfigs\{serverid}.json", json);
To create your JSON without square brackets, simply omit the list when you serialize:
var _data = new data() {
mute = $"{Role.Name}"
};
string json = JsonConvert.SerializeObject(_data);
File.WriteAllText(#$".\serverconfigs\{serverid}.json", json);
This will generate: {"mute" : "CobraMute"} assumuing that Role.Name is CobraMute
That's not a valid json. You would need to create a class with an array. Then when you serialize that class it would be serialized like this :
{"_data":[{"mute":"CobraMute"}]}
In your code, it would be like this :
class Program
{
YourClass myclass = new YourClass();
myclass._data = new List<data>();
myclass._data.Add(new data()
{
mute = $"{Role.Name}"
});
string json = JsonConvert.SerializeObject(myclass);
File.WriteAllText(#$".\serverconfigs\{serverid}.json", json);
}
class YourClass{
public List<data> _data;
}
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"
]
}
I would like to add a new item at the back of a list, and get the newly created item.
Let's assume that we could do something like this for one moment:
class Temp
{
public string First { get;set;}
public string Second { get;set;}
}
List<string> list = new List<string>();
var newItem = list.Push();
newItem.First="asd";
newItem.Second = "qwe;
this would be easier than
var newItem = new Temp();
newItem.First="asd";
newItem.Second = "qwe;
list.Add(newItem);
especially when I can't use auto-properties.
Is this possible?
Unless you implement your own List type and add the Push method, the only way you can do that is if the T in List can be constructed using a parameterless constructor.
Here's an extension method for that.
This is not recommended, but is an answer to your question.
Something along the lines of this - I did not compile or run this code
public static class ListEx {
public static T Push<T>(this List<T> list) where T: new() {
// Create an instance of T.
var instance = new T();
// Add it to the list.
list.Add(instance);
// Return the new instance.
return instance;
}
}
You can use object initializers:
var list = new List<Temp>();
list.Add(new Temp{ First = "abc", Second = "def" });
Or together with a collection initializer:
var list = new List<Temp> { new Temp{ First = "abc", Second = "def" } };
This turns your four liner into a one liner.
Or with more than one entry:
var list = new List<Temp> {
new Temp{ First = "abc", Second = "def" },
new Temp{ First = "ghi", Second = "jkl" },
new Temp{ First = "mno", Second = "pqr" }
};
And it should of course be a list of Temp instead of a list of string.
My code is below. I am not able to extract the 'name' and 'query' lists
from the JSON via a DataContracted Class (below)
I have spent a long time trying to work this one out, and could really do
with some help...
My Json string:
{"as_of":1266853488,"trends":{"2010-02-22
15:44:48":[{"name":"#nowplaying","query":"#nowplaying"},{"name":"#musicmonday","query":"#musicmonday"},{"name":"#WeGoTogetherLike","query":"#WeGoTogetherLike"},{"name":"#imcurious","query":"#imcurious"},{"name":"#mm","query":"#mm"},{"name":"#HumanoidCityTour","query":"#HumanoidCityTour"},{"name":"#awesomeindianthings","query":"#awesomeindianthings"},{"name":"#officeformac","query":"#officeformac"},{"name":"Justin
Bieber","query":"\"Justin Bieber\""},{"name":"National
Margarita","query":"\"National Margarita\""}]}}
My code:
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(this.Auth.UserName, this.Auth.Password);
string res = wc.DownloadString(new Uri(link));
//the download string gives me the above JSON string - no problems
Trends trends = new Trends();
Trends obj = Deserialise<Trends>(res);
private T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
obj = (T)serialiser.ReadObject(ms);
ms.Close();
return obj;
}
}
[DataContract]
public class Trends
{
[DataMember(Name = "as_of")]
public string AsOf { get; set; }
//The As_OF value is returned - But how do I get the
//multidimensional array of Names and Queries from the JSON here?
}
I've run into this very issue while developing Twitterizer. The issue is that the dataset isn't in a traditional object-oriented design.
If you were to map that as objects, you would see:
object root
int as_of
object trends
array[object] <date value of as_of>
string query
string name
As you can see, the trend object has a property that's name changes. The name is based on the as_of date value. As such, it can't be automatically deserialized.
My first solution was to use System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(). That method returns a hierarchy of weakly typed, nested dictionary instances. I then stepped through the results myself.
internal static TwitterTrendTimeframe ConvertWeakTrend(object value)
{
Dictionary<string, object> valueDictionary = (Dictionary<string, object>)value;
DateTime date = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds((int)valueDictionary["as_of"]);
object[] trends = (object[])((Dictionary<string, object>)valueDictionary["trends"])[date.ToString("yyyy-MM-dd HH:mm:ss")];
TwitterTrendTimeframe convertedResult = new TwitterTrendTimeframe()
{
EffectiveDate = date,
Trends = new Collection<TwitterTrend>()
};
for (int i = 0; i < trends.Length; i++)
{
Dictionary<string, object> item = (Dictionary<string, object>)trends[i];
TwitterTrend trend = new TwitterTrend()
{
Name = (string)item["name"]
};
if (item.ContainsKey("url"))
{
trend.Address = (string)item["url"];
}
if (item.ContainsKey("query"))
{
trend.SearchQuery = (string)item["query"];
}
convertedResult.Trends.Add(trend);
}
return convertedResult;
}
It's ugly, but it worked.
I've since embraced the use of Json.NET for it's speed and simplicity.
have you considered using JSON.net ?
Consider this example:
public struct TwitterResponse
{
public int32 as_of;
public Trend[] Trends;
}
public struct Trends
{
public String name;
public String query;
}
Trend[] obj = JavaScriptConvert.DeserializeObject<TwitterResponse>( res ).Trends;
Probably needs finetuning, but that's the general idea on how to do it.