I have the following object:
public class TestModel
{
public object TestValue { get; set; }
}
My database contains strings in JSON format e.g.
string dbValue1 = "[\"test value\"]"
string dbValue2 = "[\"one value\",[\"another value|or this value\"]]"
int dbValue3 = 1
bool dbValue4 = true
And I need to deserialize these values to the TestModel.TestValue property so that when I serialize the object I get the same format that is stored in the database. I can obviously get an int or bool an a basic array to work, but I can't in the case of a slightly more complex array. From the dbValue2 above I would want the output to be:
"testValue" : ["one value",["another value|or this value"]]
Now, I am using ServiceStack.Text and so far this is what I've tried:
TestValue = JsonSerializer.DeserializeFromString(dbValue, typeof(object))
TestValue = dbValue.FromJson<object>()
TestValue = JsonObject.Parse(dbValue)
And these generate:
"testValue":"[one value,[another value|or this value]]"
"testValue":{"one value":["another value|or this value"]}
"testValue":{"one value":["another value|or this value"]}
I can understand why these would not work, but I can't figure out how to do what I need.
Any help would be much appreciated.
It is because the root element is an array in the JSON. ServiceStack seems to choke on that.
If you try it with ServiceStack and add a root object with the same array as a property e.g.
var json = "{\"root\":[\"one value\",[\"another value|or this value\"]]}";
var testValue = JsonObject.Parse(json);
Console.WriteLine(testValue.ToJson());
It serializes the array correctly.
Json.Net seems to just work though.
var json = "[\"one value\",[\"another value|or this value\"]]";
var testValue = JsonConvert.DeserializeObject(
Console.WriteLine(JsonConvert.SerializeObject(testValue));
Annoying :)
Related
given an apparently invalid json
(which comes from google)
https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=de&dt=t&q=Science
of
[[["Wissenschaft","Science",,,2]],,"en"]
i want to get the values of Wissenschaft and Science
if figured out a very inelegant way to do it with Json.net via
string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"] ";
var obj = JsonConvert.DeserializeObject<List<dynamic>>(h);
JArray arr1 = obj[0];
var arr2 = arr1.First;
var x = arr2.First.Next;
string s = x.ToString();
is there some better, less verbose way ?
Here is a more concise version, maybe somebody has one which also retains
the other values from the top array
string h = "[[[\"Wissenschaft\",\"Science\",,,2]],,\"en\"]";
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Error = (serializer, err) =>
{
err.ErrorContext.Handled = true;
//ignore all errors
};
var obj = JsonConvert.DeserializeObject<List<List<List<dynamic>>>>(h,settings);
string strWissenschaft = obj[0][0][0];
string strScience = obj[0][0][1];
As you see i only care for the values in the most nested array, the other values are lost.
For first this is not valid JSON object but nevermind as you said Json.NET will parse it by adding null values into empty commas.
Because this is not valid object and it is just an array in some JSON format. There will probably no better way then parse it into dynamic List as you already did.
In case of { } at start and end and some keys:values format you can deserialize it into C# object according to class which you can define.
I am parsing tons of different jsons which only have the first Property in common.
Depending on the value of this first property I parse the json into different object and also handle possible error differently. However it happens that the json is not valid but I still want to know the value of the first property (as long as this is valid) so I can handle the parsing error. I was wondering if this is possible with Json.Net. Of course I assume that at least the first property is valid, something like this for example:
{
"parsingType":"sometype",
"someothervalue":123,
"someval"123,
}
I tried the following but since the exception is thrown when using .Parse I get no result:
JToken jtoken = JToken.Parse(json);
var theValueIWantToGet = jtoken["parsingType"].Value<string>();
I dont think any parsing engine parses json partially. You will have to parse your json string by yourself if parser fails
string json = "{ \"parsingType\":\"sometype\", \"someothervalue\":12}";
var props = json.Replace('{',' ').Replace('}',' ').Split(',').ToList();
if (props.Count > 0)
{
var firstProp = props[0].Split(':');
var propName = firstProp[0];
var propVal = firstProp[1];
}
You can use a JsonReader (probably JsonTextReader as the concrete type) to parse the JSON as a stream, a bit like XmlReader. So for example:
using System;
using System.IO;
using Newtonsoft.Json;
public class Test
{
static void Main(string[] args)
{
using (var reader = new JsonTextReader(File.OpenText("test.json")))
{
while (reader.Read())
{
Console.WriteLine(reader.TokenType);
Console.WriteLine(reader.Value);
}
}
}
}
On the JSON you've provided, that will give output of:
StartObject
PropertyName
parsingType
String
sometype
PropertyName
someothervalue
Integer
123
Unhandled Exception: Newtonsoft.Json.JsonReaderException [...]
So if you always expect there to be a start object, then a property name, then a string property value, you could easily validate that that's the case and extract the property value.
I am very new to programming and not sure where I am going wrong. I have read the other threads with similar error, but I think my problem is even basic.
I get a string generated which contains XML, but it doesnt start with an XML. When I try to parse that string I get the above error.
Is there a way of getting rid of the text and save the text from where the XML starts?
My string:
{"Id":"6a76f781-f592-4320-a116-6ab289505423","Name":"Test - A","AttachmentRequired":false,"FormXml":"
<?xml version=\"1.0\" encoding=\"utf-16\"?>
The easiest way would be to use a JSON parser like Newtonsoft:
public class Data
{
public string Id;
public string Name;
public bool AttachmentRequired;
public string FormXml;
}
var o = JsonConvert.DeserializeObject<Data>(json);
var xml = o.FormXml;
Here is the Nuget package to Newtonsoft which I demonstrated above:
https://www.nuget.org/packages/Newtonsoft.Json/
If you absolutely can't use an external library to transform it into a CLR object, here is how you would do it through string manipulation:
var str = #"{ ""Id"":""6a76f781-f592-4320-a116-6ab289505423"",""Name"":""Test - A"",""AttachmentRequired"":false,""FormXml"":""<?xml version=\""1.0\"" encoding=\""utf-16\""?>""}";
var parts = str.Split(':');
var last = parts[parts.Length -1];
var xml = last.Replace("}","").Replace("\"<","<").Replace(">\"",">");
your string appears to be in json format and xml part of it is a field value for "formxml". screenshot
Easy way is to deserialize the string into object using newtonsoft json, and then parse the value of formxml to your object.
JsonConvert.DeserializeObject<YourClass>(yourstring);
Say I have a string representing an array of objects in JSON form:
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
What I want is an array of strings, each string being the string representation of a JSON object - NOT the object itself. It should look something like this:
string[] s = new string[]
{
"{\"name\":\"Person1\"}",
"{\"name\":\"Person2\"}"
};
1) Almost every search I attempt pulls up millions of results on how to simply deserialize a JSON string using (eg) Json.NET. This is not what I want to do.
2) I have tried building a class representing the objects to temporarily loop through a deserialize/serialize mapping each to a string in an array, but the schema for the objects is variable (hence why I only need a string representation).
3) I have attempted a few regex to try and do this, but my JSON string can contain fields that contain JSON strings as their value (icky, but out of my control) and so nested character escaping etc drove me partially mad before I decided to beg for help here.
Surely this should be simple? Anybody got any pointers?
You'll need to deserialize it, and then serialize each object independently.
For example (using Newtonsoft.Json):
string json = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var objects = JsonConvert.DeserializeObject<List<object>>(json);
var result = objects.Select(obj => JsonConvert.SerializeObject(obj)).ToArray();
Yields (as a string[]):
{"name":"Person1"}
{"name":"Person2"}
If you try to avoid deserializing and serializing, you're almost certain to run into an edge case that will break your code.
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
var Json = JsonConvert.DeserializeObject<List<object>>(s);
string[] Jsonn = Json.Select(x => x.ToString()).ToArray();
[] Jsonn returns string array instead of object array with JObject formatted.
Hope this one help you.
Why don't you just use this
string s = "[{\"name\":\"Person1\"},{\"name\":\"Person2\"}]";
string[] t = s.Split(',');
I tried it. It simply gives you string array as you want it....
How can I get the length of a JSON Array I get using json.net in C#? After sending a SOAP call I get a JSON string as answer, I use json.net to parse it.
Example of the json I got:
{"JSONObject": [
{"Id":"ThisIsMyId","Value":"ThisIsMyValue"},
{"Id":"ThisIsMyId2","Value":"ThisIsMyValue2"}
]}
And I parse it and write it in console:
var test = JObject.Parse (json);
Console.WriteLine ("Id: {0} Value: {1}", (string)test["JSONObject"][0]["Id"], (string)test["JSONObject"][0]["Value"]);
This works like a spell, only I don't know the length of the JSONObject, but I need to do it in a for loop. I only have no idea how I can get the length of test["JSONObject"]
But something like test["JSONObject"].Length would be too easy I guess :(..
You can cast the object to a JArray and then use the Count property, like so:
JArray items = (JArray)test["JSONObject"];
int length = items.Count;
You can then loop the items as follows:
for (int i = 0; i < items.Count; i++)
{
var item = (JObject)items[i];
//do something with item
}
According to Onno (OP), you can also use the following:
int length = test["JSONObject"].Count();
However, I have not personally confirmed that this will work
The easiest and cleanest way I found:
int length = test["JSONObject"].Count;
You can use below line to get the length of JSON Array in .Net (JArray) .
int length = ((JArray)test["jsonObject"]).Count;
Just try this:
var test= ((Newtonsoft.Json.Linq.JArray)json).Count;
This worked for me supposing the json data is in a json file.
In this case, .Length works but no intellisence is available:
public ActionResult Index()
{
string jsonFilePath = "C:\\folder\\jsonLength.json";
var configFile = System.IO.File.ReadAllText(jsonFilePath);
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(configFile);
var jsonObject = d["JSONObject"];
int jsonObjectLength = jsonObject.Length;
return View(jsonObjectLength);
}