var test = {'abc':76,'data':'[6435,3310,56.06875]'}
how do I convert above json string to an object say:
class item
{
public string abc {Get;set;}
public float[] data {get;set}
}
I tried JsonConvert.DeserializeObject<item>(test);
but get this error:
{"Error converting value \"[6435,3310]\" to type 'System.Single[]'. Path 'data', line 1, position 117."}
There are a few problems with the json string (i am assuming you are using C#). First of the values of the data
property are actually a string (given the quotes). Which is why you are getting the error.
What you could do is create a property to hold the string and then another property to parse the float
values after parsed. This is done by using a few JSON.Net attributes of JsonProperty
and JsonIgnore
. These attributes tell the serializer what the property name is in the json string and which properties to ignore.
class Foo
{
string dataString;
float[] data = null;
[JsonProperty("abc")]
public string Abc { get; set; }
[JsonProperty("data")]
public string DataString
{
get { return dataString; }
set
{
data = null;
dataString = value;
}
}
[JsonIgnore]
public float[] Data
{
get
{
if (data != null)
return data;
return data = dataString != null ? JsonConvert.DeserializeObject<float[]>(DataString) : null;
}
set
{
DataString = value == null ? null : JsonConvert.SerializeObject(value);
}
}
}
This looks like alot of code however uses backing fields to allow you to change both the Data
field and the DataString
field while maintaining a working serializer.
This is then simply called using
var i = JsonConvert.DeserializeObject<Foo>(test);
This might do the trick for you
string jsn = @"{'abc':76,'data':'[6435,3310,56.06875]'}";
jsn = jsn.Replace("'[", "[");
jsn = jsn.Replace("]'", "]");
var ser = JsonConvert.DeserializeObject<ClsResult>(jsn);
I have used replace because 'data':'[6435,3310,56.06875]'
is making the array of data to string. So better we make it like 'data':[6435,3310,56.06875]
and then you class would look like
public class ClsResult
{
[JsonProperty("abc")]
public int abc { get; set; }
[JsonProperty("data")]
public IList<double> data { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.