Invalid JSON primitive when deserializing - c#

Alright, so having this issue when I try to run my application:
Invalid JSON primitive: .
public static void ReloadConfig()
{
if (!File.Exists("config.cfg"))
{
StringBuilder sb = new StringBuilder();
sb.Append("{\r\n");
sb.Append("\"Admins\":[76561198214617172],\r\n");
sb.Append("\"Chatty\":false,\r\n");
sb.Append("}");
File.WriteAllText("config.cfg", sb.ToString());
}
try
{
JavaScriptSerializer jss = new JavaScriptSerializer();
config = jss.Deserialize<Roles>(File.ReadAllText("config.cfg"));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
ReloadConfig();
}
}
And this is how the config looks like when it's generated:
{
"Admins":[76561198214617172],
"Chatty":false,
}
As from my error message I would assume it says I have a space in my config, but I do not have that.
And if that matters I use System.Web.Script.Serialization.

You have an errant comma in your output after false:
{
"Admins":[76561198214617172],
"Chatty":false,
}
Should be:
{
"Admins":[76561198214617172],
"Chatty":false
}

You need to remove the comma after false:
{
"Admins":[76561198214617172],
"Chatty":false
}
I used JSONLint to validate your JSON, there are many other online JSON validators.

Related

How to validate JSON objects using Newton JSON and C#

I am new to Tests in Visual Studio , normally I always used proper test tool in order to validate the json file and its data
I am stuck how to validate JSON objects , data inside in the JSON File
through following code I am Reading the JSON file , further i would like to validate the JSON objects
here is my readJSON method which reads the file but now I would like to either check if it contains any given specific value let say I would like to check if it contains the "Details" and its value "XYZG" or not
I tried to convert JSON into ToString() and then user .count method but it gives me the value 0 in output so I removed that ToString() block from the code
JSON Data
{
"Details":"XYZG",
"City":"Tokyo",
"Id":"ATOOO",
"Name":"Johny"
}
read json method
public string ReadMyJsonFile(String FilePath)
{
string storeValue = "";
using (StreamReader readerobject = new StreamReader(FilePath))
{
string jsonString = readerobject.ReadToEnd();
}
return storeValue;
}
TestMethod
public async TaskTest()
{
var json = ReadMyJsonFile(#"FilePath/Test.json");
var testobject = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(testobject);
try
{
if (testobject.SelectTokens("$..Id").Any(t => t.Value<string>() == "$..Id"))
{
Console.WriteLine("\n \n value exist");
}
}
catch (Exception ex)
{
Console.WriteLine("error keyword");
}
}
ยดยดยด
I am kinda stuck with the validation part of my json data
you better print a json string, not a JObject
try
{
var json = ReadMyJsonFile(#"FilePath/Test.json");
if (!string.IsNullOrEmpty(json))
{
Console.WriteLine("json file exists \n");
Console.WriteLine(json);
}
else
{
Console.WriteLine("json file not exists \n");
return;
}
var testObject = JObject.Parse(json);
if (!string.IsNullOrEmpty((string)testObject["Id"]))
{
Console.WriteLine("\n Id value exists");
Console.WriteLine((string)testObject["Id"]);
}
else
Console.WriteLine("\n Id value doesnt exist");
}
catch (Exception ex)
{
Console.WriteLine("error "+ex.Message);
}

how to get code and message node value from given json message in c#

Need to get value of code and message
{
"status":null,
"msg":null,
"txn":[
{
"code":"0",
"message":"valid.",
"match":"100",
"name":null,
"number":"02100172117301",
"id":"01"
}
]
}
You can try to use Newtonsoft JSON
data = JObject.Parse(yourJson);
string code = data.txn[0].code;
string message = data.txn[0].message;

System.JSON does not throw exception for malformed JSON input

I am new to using .NET System.JSON. Trying to learn, using this sample application.
[DataContract]
internal class Person
{
[DataMember]
internal string name;
[DataMember]
internal int age;
}
String strData = "{ \"Person\": [{\"name\":\"TSR\",\"age\": 4 },{\"name\":\"KV\",\"age\":10}]}";
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strData));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
Person jsonArray = (Person)ser.ReadObject(ms) as Person;
I was testing the program by giving a sample input as this. Note the last curley bracket is missing in the input. I was expecting the program to throw some sort of exception but it's not. Is this an expected behavior with System.JSON?
"{ \"Person\": [{\"name\":\"TSR\",\"age\": 4 },{\"name\":\"KV\",\"age\":10}]";
The below input has an extra curley brace at the end. No exception is thrown for this input as well.
"{ \"Person\": [{\"name\":\"TSR\",\"age\": 4 },{\"name\":\"KV\",\"age\":10}]}}";
Tell System.Json to Parse your string to a JsonValue. If it's valid, it will pass - if not, it should throw an exception
try
{
var validJson = JsonValue.Parse(strData);
}
catch (FormatException e)
{
//Invalid Json Format
Console.WriteLine(e);
}
catch (Exception e)
{
//some other exception
}

streamreader issue with using a textbox

I'm new to C# and writing this application that displays a message if the given name in the TextBox is in the popular list file. My book gives very little help to fix this, my error is the inputfile of if(boy.Contains(boyinputFile)) same for the girl where it says something about:
cannot convert to string.
private void checkName_Click(object sender, EventArgs e)
{
string boy;
string girl;
girl = girlBox.Text;
boy = boyBox.Text;
StreamReader boyinputFile;
StreamReader girlinputFile;
boyinputFile = File.OpenText("BoyNames.txt");
girlinputFile = File.OpenText("GirlNames.txt");
while (!boyinputFile.EndOfStream)
{
if (boyBox.Text.Contains(boyinputFile))
{
MessageBox.Show("Yes, your name is popular!");
}
}
while (!girlinputFile.EndOfStream)
{
if (girl.Contains(girlinputFile))
{
MessageBox.Show("Yes, your name is popular!");
}
else
{
MessageBox.Show("Sorry, couldn't find your name.");
}
}
boyinputFile.Close();
girlinputFile.Close();
}
You need to convert your stream to a string. This is where you are getting your error:
cannot convert to string
string girl_file = streamReader.ReadToEnd();
You then need to see if the selected name is within the string file. You need to reverse your check. You are checking to see if the textbox contains the file.
if (girl_file.Contains(girl))
{
MessageBox.Show("Yes, your name is popular!");
}
Also have a look at this question How do I convert StreamReader to a string?
I want to give you better code than the existing answers show you.
var lines = File.ReadAllLines("...");
var isMatch = lines.Contains(name);
It really can be that simple.
Try this:
string boy = boyBox.Text;
using (StreamReader sr = new StreamReader("D:\\BoyNames.txt"))
{
string boyinputFile = sr.ReadToEnd();
if (boyinputFil.Contains(boy))
{
MessageBox.Show("Yes, your name is popular!");
}
else
{
MessageBox.Show("Sorry, couldn't find your name.");
}
}
Replace this line
if (boyBox.Text.Contains(boyinputFile))
with
if (boyBox.Text.Contains(boyinputFile.ToString())).

.NET, Why must I use *Specified property to force serialization? Is there a way to not do this?

I am using xml-serialization in my project to serialize and deserialize objects based on an xml schema. I used the xsd tool to create classes to use when serializing / deserializing the objects.
When I go to serialize the object before sending, I am forced to set the *Specified property to true in order to force the serializer to serialize all propeties that are not of type string.
Is there a way to force the serialization of all properties without having to set the *Specified property to true?
The FooSpecified property is used to control whether the Foo property must be serialized. If you always want to serialize the property, just remove the FooSpecified property.
I know this is an old question, but none of the other answers (except perhaps the suggestion of using Xsd2Code) really produces an ideal solution when you're generating code as part of your build and your .xsd may change several times during a single release cycle.
An easy way for me to get what I really wanted and still use xsd.exe was to run the generated file through a simple post-processor. The code for the post-processor is as follows:
namespace XsdAutoSpecify
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length != 1)
{
throw new ArgumentException("Specify a file name");
}
string fileName = args[0];
Regex regex = new Regex(".*private bool (?<fieldName>.*)Specified;");
IList<string> result = new List<string>();
IDictionary<string, string> edits = new Dictionary<string, string>();
foreach (string line in File.ReadLines(fileName))
{
result.Add(line);
if (line.Contains("public partial class"))
{
// Don't pollute other classes which may contain like-named fields
edits.Clear();
}
else if (regex.IsMatch(line))
{
// We found a "private bool fooSpecified;" line. Add
// an entry to our edit dictionary.
string fieldName = regex.Match(line).Groups["fieldName"].Value;
string lineToAppend = string.Format("this.{0} = value;", fieldName);
string newLine = string.Format(" this.{0}Specified = true;", fieldName);
edits[lineToAppend] = newLine;
}
else if (edits.ContainsKey(line.Trim()))
{
// Use our edit dictionary to add an autospecifier to the foo setter, as follows:
// set {
// this.fooField = value;
// this.fooFieldSpecified = true;
// }
result.Add(edits[line.Trim()]);
}
}
// Overwrite the result
File.WriteAllLines(fileName, result);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(-1);
}
}
}
}
The result is generated code similar to the following:
[System.Xml.Serialization.XmlAttributeAttribute()]
public barEnum foo {
get {
return this.fooField;
}
set {
this.fooField = value;
this.fooFieldSpecified = true;
}
}
You could add a default value to your schema and then use the DefaultValueAttribute.
For example, you could have the following in your schema:
<xs:element name="color" type="xs:string" default="red"/>
And then the following property for serialization:
[DefaultValue(red)]
public string color { get; set; }
This should force the color property to always serialize as "red" if it has not been explicitly set to something else.
I faced same issue and ended up setting all *Specified properties to true by reflection.
Like
var customer = new Customer();
foreach (var propertyInfo in typeof(Customer).GetProperties().Where(p => p.Name.EndsWith("Specified")))
{
propertyInfo.SetValue(customer, true);
}
We found that the answer to this question is to make sure that the schema elements are all defined as string data types. This will make sure that the serializer serializes all fields without the use of the correlated *specified property.

Categories

Resources