Reputation: 1408
I'm trying to parse to a C# object a string containing a JSON that looks like that : I know it's not really valid json but I can't choose it, it's sent by a device. That's why I've tried to replace the [] by {} to make it look like a valid object.
[2, "2", "text", {Object}]
I've created the following class:
public class MyClass
{
[JsonProperty(Order = 0)]
public int TypeRequest { get; set; }
[JsonProperty(Order = 1)]
public string UniqueID { get; set; }
[JsonProperty(Order = 2)]
public string Action { get; set; }
[JsonProperty(Order = 3)]
public JObject Payload { get; set; }
}
I want to parse the {Object} later (I need to know the "Action" property first because the object depends on the action).
So far I've done :
string userMessage = "[2, "2", "text", {Object}]";
if (userMessage.Length > 2)
{
// We need to remove the first [ and the last ] to be able to parse into a json object
StringBuilder sb = new StringBuilder(userMessage);
sb[0] = '{';
sb[sb.Length - 1] = '}';
userMessage = sb.ToString();
}
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyClass objectJSON = jsonSerializer.Deserialize<MyClass >(userMessage);
But it doesn't work I get the following exception:
Invalid object passed in, ':' or '}' expected. (3): {Object}}
I've also tried with JObject.Parse instead and I got:
Invalid JavaScript property identifier character: ,. Path '', line 1, position 2.
Do you know how to do it? I would like to avoid having to split my JSON by commas and have the cleanest way to do it.
Upvotes: 2
Views: 3757
Reputation: 44680
It's not really a valid JSON because of {Object}
so I removed it. You can technically do json.Replace("{Object}", "something else")
to make it easier. Because you deal with different types in array, it may not be a one step process. Here is an idea for you:
var json = "[2, \"2\", \"text\"]";
var array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
switch (item.Type)
{
case JTokenType.Integer:
// todo: your parsing code
break;
case JTokenType.String:
break;
// etc.
}
}
I used JSON.NET library to parse JSON. You can install it using nuget:
Install-Package Newtonsoft.Json
If you can, I'd recommend you to fix the JSON source to provide you with a valid JSON that can be parsed to an object without use of low-level classes like JToken
, JArray
, JObject
etc.
Upvotes: 3