So I am sending some values to a javascript array. Currently it is an array called data, that has two elements, value and color, for example:
var data = [{value:226,color:"#FFFFF"},{value:257,color:"#FFFFF"}];
The problem is that color should be color: #FFFFF WITHOUT the " surrounding. The C# is as follows:
[JsonObject(MemberSerialization.OptIn)]
public class StatsValues
{
[JsonProperty]
public int value { get; set; }
[JsonProperty]
public string color { get; set; }
}
var values = new List<StudentBrandsApp.Models.StatsValues>();
foreach (DataRow dr in statsDataTable.Rows)
{
values.Add(new StudentBrandsApp.Models.StatsValues() { value = Convert.ToInt32(dr.ItemArray[1].ToString()), color = "#FFFFF" });
}
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter);
writer.QuoteName = false;
serializer.Serialize(writer, values);
writer.Close();
var json = stringWriter.ToString();
ViewData["json"] = json;
How do I serialise this so that color excludes the quotes and returns simply the hash value?
Please try your json string to below format:
{
"array": [
{
"value":226,
"color":"#FFFFF"
},
{
"value":226,
"color":"#FFFFF"
}
]
}
or
var data = [{"value":226,"color":"#FFFFF"},{"value":257,"color":"#FFFFF"}];
Related
I keep getting "Additional text encountered after finished reading JSON content" when deserializing. I've tried placing the whole "output" into square brackets, didn't work out.
Full error message
Newtonsoft.Json.JsonReaderException:
'Error reading JObject from JsonReader. Current JsonReader item is not an object:
StartArray. Path '', line 1, position 1.'
These are my 2 objects. NOTE: Values are currently commented for easier "output" reading.
class ItemSerObj
{
public string ItemName { get; set; }
/*
public string Value { get; set; }
public string Quality { get; set; }
public string TimeStamp { get; set; }*/
}
.
class GroupSerObj
{
public string GroupName { get; set; }
/*
public string UpdateRate { get; set; }
public string Active { get; set; }*/
public List<ItemSerObj> Items { get; set; }
}
How I serilzed them.
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(path + "\\data.txt"))
{
using (JsonWriter writer = new JsonTextWriter(sw))
{
foreach (ListViewItem group in lV_groups.Items)
{
List<ItemSerObj> itemsObj = new List<ItemSerObj>();
tempOPCServer.opcGroup = tempOPCServer.opcServer.OPCGroups.GetOPCGroup(group.SubItems[0].Text);
foreach (OPCItem item in tempOPCServer.opcGroup.OPCItems)
{
ListViewItem listViewItem = new ListViewItem();
listViewItem.Name = item.ItemID.Substring(item.ItemID.LastIndexOf('.') + 1);
itemsObj.Add(
new ItemSerObj
{
ItemName = listViewItem.Name
/*ItemName = item.SubItems[0].Text/*,
Value = item.SubItems[1].Text,
Quality = item.SubItems[2].Text,
TimeStamp = item.SubItems[3].Text*/
});
}
GroupSerObj serializeGroup = new GroupSerObj
{
GroupName = group.SubItems[0].Text,/*
UpdateRate = group.SubItems[1].Text,
Active = group.SubItems[2].Text,*/
Items = itemsObj
};
serializer.Serialize(writer, serializeGroup);
}
}
}
The output.
{"GroupName":"Group0","Items":[{"ItemName":"Int1"},{"ItemName":"Money"},{"ItemName":"Int4"},{"ItemName":"Int2"}]}{"GroupName":"Group1","Items":[]}{"GroupName":"Group2","Items":[]}
More readable sorting
{"GroupName":"Group0","Items":[
{"ItemName":"Int1"},
{"ItemName":"Money"},
{"ItemName":"Int4"},
{"ItemName":"Int2"}]}
{"GroupName":"Group1","Items":[
]}
{"GroupName":"Group2","Items":[
]}
What I've tried to deserialize it.
string fromJson;
using (StreamReader sr = new StreamReader(path + "\\data.txt"))
{
fromJson = #sr.ReadLine();
}
JObject fromJsonObject = JObject.Parse(fromJson); //Where exeption occurs.
IList<JToken> results = fromJsonObject["Items"]["ItemName"].Children().ToList();
IList<GroupSerObj> deserResults = new List<GroupSerObj>();
foreach(JToken result in results)
{
GroupSerObj deserResult = result.ToObject<GroupSerObj>();
deserResults.Add(deserResult);
}
For me it looks like your output is wrong. Its an array of objects (multiple groups) so it should be surrounded by [ and ] and each object separated by a comma (,).
Your output should look like this:
[{"GroupName":"Group0","Items":[{"ItemName":"Int1"},{"ItemName":"Money"},{"ItemName":"Int4"},{"ItemName":"Int2"}]},{"GroupName":"Group1","Items":[]},{"GroupName":"Group2","Items":[]}]
You are using a JObject to Parse the Array, but when paring an array we need the JArray, so it should be:
JArray fromJsonObject = JArray.Parse(fromJson); //Where exeption occurs.
for (int i = 0; i < fromJsonObject.Count; i++)
{
IList<GroupSerObj> deserResults = new List<GroupSerObj>();
var deserResult = fromJsonObject[i].ToObject<GroupSerObj>();
deserResults.Add(deserResult);
}
I have problem with serialization and deserialization in JSON
I've made 2 tasks to read from JSON file which looks like this:
[
{
"ID": 1,
"OIB": 123456789,
"ime": "name",
"prezime": "surname",
"grad": "city"
}
]
Now I have to add another client with ID 2, with new user informations.
I can read this JSON file with no problems, but I am stuck on writing into the same file.
public struct Klijent
{
public int ID { get; set; }
public long OIB { get; set; }
public string ime { get; set; }
public string prezime { get; set; }
public string grad { get; set; }
}
"FetchClient" from JSON
public static List<Klijent> DohvatiKlijente()
{
List<Klijent> lKlijent = new List<Klijent>();
StreamReader klijent = new StreamReader("x");
string sJson = "";
using (klijent)
{
sJson = klijent.ReadToEnd();
lKlijent = JsonConvert.DeserializeObject<List<Klijent>>(sJson);
}
return lKlijent;
}
"AddClient" to JSON
OIB -> personal identificator
ID -> should go +1 with every entry of client
grad -> city
ime -> name
prezime -> surname
public static void DodavanjeKlijenata()
{
Console.Write("Unesite OIB klijenta: ");
string pOIB = Console.ReadLine();
long nullOIB = 0;
long.TryParse(pOIB, out nullOIB);
int id = 0;
Console.Write("Unesite ime klijenta: ");
string ime1 = Console.ReadLine();
Console.Write("Unesite prezime klijenta: ");
string prezime1 = Console.ReadLine();
Console.Write("Unesite grad klijenta: ");
string grad1 = Console.ReadLine();
List<Klijent> lKlijent = DohvatiKlijente();
foreach (var Klijent in lKlijent)
{
id = Klijent.ID + 1;
}
Klijent dKlijent = new Klijent()
{
ID = id,
OIB = nullOIB,
ime = ime1,
prezime = prezime1,
grad = grad1
};
var serializer = new JsonSerializer();
using (var sw = new StreamWriter("x"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, dKlijent);
}
}
This code does work, but it seems to delete every time my JSON file and it's format is in one line only, I would like to have it in multiple lines.
Thank you :)
There are two things that you need to do here
Ensure new Client is appended to existing list
For this you can add the new client to the List
lKlijent.Add(dKlijent);
Now you need to serialize the List, instead of lKlijent
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, lKlijent);
}
Formatting
For formatting you can use Formatting Settings. For example,
var serializer = new JsonSerializer() { Formatting = Formatting.Indented} ;
Additional Comments
1. Calculation of ID
Instead of calculating the new ID using the following loop,
foreach (var Klijent in lKlijent)
{
id = Klijent.ID + 1;
}
You could use Enumerable.Last() to get the last client in the list. For example,
var id = lKlijent?.Any()!=true? 0:lKlijent.Last().ID;
2. Rewriting DohvatiKlijente method
The DohvatiKlijente method could rewritten as
public static List<Klijent> DohvatiKlijente()
{
return JsonConvert.DeserializeObject<List<Klijent>>(File.ReadAllText("C:\\Users\\Hrvoje\\Desktop\\Polica Osiguranja MAIN\\Polica Osiguranja\\klijent.json"));
}
Similarly, writing back to file can be simplified as
var jsonString = JsonConvert.SerializeObject(lKlijent,Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(outputFilePath,jsonString);
Is it possible to convert ordinary string like:
"Data: {
id: '288dsbshbdas8dsdsb',
data: '2pm'
}"
to:
Data: {
id: '288dsbshbdas8dsdsb',
data: '2pm'
}
Have tried like that:
string input = "Data: {id: '288dsbshbdas8dsdsb', data: '2pm'};
var output = Convert.ChangeType(input, TypeCode.Object);
But this still returns string?
Using NewtonSoft JsonTextWriter, and JsonTextReader You can easly write and read this kind of string.
For writing your must use JsonTextWriter property:
writer.QuoteName = false;
writer.QuoteChar = '\'';
To read to custom configuration is needed.
using System;
using System.IO;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var objSource= new RootObject{
Data= new Data{
id="123456",
data="FooBar"
}
};
var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter);
writer.QuoteName = false;
writer.QuoteChar = '\'';
serializer.Serialize(writer, objSource);
var input= stringWriter.ToString();
Console.WriteLine(input);
JsonTextReader reader = new JsonTextReader(new StringReader(input));
var result = serializer.Deserialize<RootObject>(reader);
result.Dump();
}
public class Data
{
public string id { get; set; }
public string data { get; set; }
}
public class RootObject
{
public Data Data { get; set; }
}
}
live demo
Disclaimer: As Jodrell noticed it return a "RootObject".
The writer will return {Data:{id:'123456',data:'FooBar'}}
instead of Data:{id:'123456',data:'FooBar'} Notice the extra {} around the string.
The string manipulation needed to get from one too the other is minor enought.
I am trying to convert my json data to c sharp understandable format so that I can use JsonConvert.SerializeObject to convert that data to JSON format and send it over HTTP protocol. My json data is as follows:
{
"m2m:ae":
{
"api": "ADN_AE_ATCARD06",
"rr": "true",
"lbl": ["AT06"],
"rn": " adn-ae_AT06"
}
}
I tried to write it in c sharp understandable format but was able to do this:
var obj = new
{
m2m = new
{
api = "ADN_AE45",
rr = "true",
lbl = new[] { "ad" },
rn = "adfrt"
}
};
var result = JsonConvert.SerializeObject(obj, Formatting.Indented);
my issue is how to include m2m:ae into my c-sharp code. I am new to json, I am able to convert only if parent object has no value but if it has value I am not able to. please help.
I was incorrect in my comment. While "m2m:ae" is not a valid name for a C# property is valid JSON. This can be accomplished by tagging the class property with JsonProperty.
Define your class like this
public class TestJson
{
[JsonProperty("m2m:ae")]
public Class2 Class2Instance { get; set; }
}
public class Class2
{
public string Api { get; set; }
public string Rr { get; set; }
public string[] Lbl { get; set; }
public string Rn { get; set; }
}
and then populate your class like this
_sut = new TestJson
{
Class2Instance = new Class2 {Api = "ADN_AE45", Rr = "true", Lbl = new[] {"ad"}, Rn = "adfrt"}
};
and serialize
_result = JsonConvert.SerializeObject(_sut, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
The resulting serialized object looks like
{
"m2m:ae": {
"api": "ADN_AE45",
"rr": "true",
"lbl": ["ad"],
"rn": "adfrt"
}
}
and deserialization is the reverse
var test = JsonConvert.DeserializeObject<TestJson>(_result, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Did you write the Json in a text file?
If yeah so fileTxt is what is written on the file(as json)
String fileTxt = File.ReadAllText(Give a path for a file); //read from file
Jobject Json = Jobject.Parse(fileTxt); //convert the string to Json
Console.WriteLine($"rr: {Json["rr"]} "); // get the rr from json and print it
Other than class method mentioned by Fran one can use the Dictionary method to create key value pair and newtonsoft.json library to convert to json.
var sub= Dictionary<string,string>
{{"abc","xyz"}
};
var main = Dictionary<string,object>
{{"wer:asd",sub}
};
string str= JsonConvert.SerializeObject(main);
This is one of my first ventures into WCF/JSON. I created a WCF Web Service. This is one of my methods. It is how I serialize the datable to JSON.
public string GetPrayers()
{
DataTable myDt = new DataTable();
myDt = sprocToDT("LoadPrayers");
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
return JSONString;
}
This returns a nice JSON Dataset:
{"GetPrayersResult":"[{\"prayerid\":2,\"prayer\":\"Please pray for my
dog Rusty. He has cancer
:(\",\"prayerCategory\":\"General\",\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayerid\":1,\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerCategory\":\"Sports\",\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]"}
When I go to deserialize it I get all nulls. Here is the classes I created:
public class PrayUpPrayers
{
public string prayer { get; set; }
public string prayerid { get; set; }
public string prayerCategory { get; set; }
public string prayerCategoryID { get; set; }
public string prayerDate { get; set; }
public string handle { get; set; }
public string country { get; set; }
}
public class ThePrayer
{
public PrayUpPrayers prayers { get; set; }
}
}
This is how I am retrieving the JSON:
void getData()
{
var request = HttpWebRequest.Create(string.Format(#"URLGoesHere"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string foo = content.ToString();
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Testing is always null? Is the issue that I am serializing it wrong, could it be the class structure, or is it related to how I am deserializing it. One important note: I checked my JSON on one of these JSONClassesFromC# sites and it only returns the GetPrayersResult as the only class item. Ignoring completely my entire structure.
You didn't provide the code for sprocToDT, but it should create ThePrayer object witch should contain list of PrayUpPrayers
public class ThePrayer
{
public List<PrayUpPrayers> prayers { get; set; }
}
And then you should deserialize ThePrayer object, not PrayUpPrayers.
For example
PrayUpPrayers prayUpPrayers1 = new PrayUpPrayers
{
prayer = "Please pray for my dog Rusty. He has cancer",
prayerid = "2",
prayerCategory = "General",
prayerDate = "2017-06-10T21:24:16.1",
handle = "GuruJee",
country = "USA"
};
PrayUpPrayers prayUpPrayers2 = new PrayUpPrayers
{
prayer = "Help Me I need a appendectomy STAT",
prayerid = "1",
prayerCategory = "Sports",
prayerDate = "2017-04-10T20:30:39.77",
handle = "GuruJee",
country = "USA"
};
ThePrayer thePrayer = new ThePrayer
{
prayers = new List<PrayUpPrayers>
{
prayUpPrayers1, prayUpPrayers2
}
};
myDt in your code should be the same as thePrayer instance in my code.
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
will provide Json that looks like
"{\"prayers\":[{\"prayer\":\"Please pray for my dog Rusty. He has
cancer\",\"prayerid\":\"2\",\"prayerCategory\":\"General\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerid\":\"1\",\"prayerCategory\":\"Sports\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]}"
And deserialize will look like
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.ThePrayer>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
that's simple. you should deserilze the output twice. try this:
var output= DeserializeObject<string>(foo);
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(output,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});