Stefan Karlsson Stefan Karlsson - 2 months ago 22
C# Question

Deserialize bad json

I have a json response from a third-party application, that looks like this:

{
1: {
number: 1,
headline: Nyttigt,
value: 9,
type: value
},
2: {
number: 4,
headline: ,
value: 0,
type: order
},
3: {
number: 5,
headline: Generellt-Sortiment/utbud,
value: 9,
type: value
},
4: {
number: 5,
headline: Generellt-Leveranser,
value: 9,
type: value
},
5: {
number: 5,
headline: ,
value: 0,
type: order
}
}


I am trying to deserialize it using ServiceStack's
JsonObject.Parse(jsonResult);


The problem is that the json gets cut:

enter image description here

How can i fix this issue?

Answer

The data you have isn't JSON but without whitespace it is valid JSV format. ServiceStack.Text supports serialising and deserialising JSV.

So given the data:

{1:{number:1,headline:Nyttigt,value:9,type:value},2:{number:4,headline:,value:0,type:order},3:{number:5,headline:Generellt-Sortiment/utbud,value:9,type:value},4:{number:5,headline:Generellt-Leveranser,value:9,type:value},5:{number:5,headline:,value:0,type:order}}

and the DTOs:

public class Item
{
    public int Number { get; set; }
    public string Headline { get; set; }
    public int Value { get; set; }
    public ItemType Type { get; set; }
}

public enum ItemType
{
    value,
    order
}

You can deserialise it:

var data = "{1:{number:1 ....";
var items = data.FromJsv<Dictionary<int,Item>> ();

So you could use a request filter to deserialise the request from JSV into your DTO.