0

I have a JSON which basically looks like this:

{
    "body": 
    {
        "mode": "raw",
        "raw": "{
            \"Token\" : \"123123\", \"queryName\" : \"testMethod\" ,\"dataTestToSEND\" :{\"IDs\":[\"B00448MZUW\",\"B071F7LBN6\",\"B01BBZJZHQ\"],\"Marketplace\":\"southAmerica\",\"Region\":\"West\",\"PricingMethod\":0}} "a
        },
        "description": "some description here"
    }
}

And when I converted it to C# object classes I got this:

public class Body
{
    public string mode { get; set; }
    public string raw { get; set; }
}

public class RootObject
{
    public Body body { get; set; }
    public string description { get; set; }
}

I used json2csharp tool here..

Now what confuses me here is the "raw" property as you can see.. The tool converted it into a string, but this doesn't really looks like a string to me?

Rather a raw, the way I see it, should be an class which contains something like this:

public class Raw
{
    public string Token { get; set; }
    public string queryName { get; set; }
    public List<string//?not sure which type does this needs to be set to?> 
    dataTestToSEND { get; set }
    public string marketplace { get; set; }
    public string Region { get; set }
}

Can someone help me out with this? How can I structure a proper set of classes and objects for this JSON? It's very confusing for me right now...

4
  • 4
    The raw property is indeed a string which contains a json document Commented Jun 13, 2017 at 9:05
  • @SirRufo and how am I supposed to structure it in that form if I have no representable set of classes and object through which I can convert it to ? Commented Jun 13, 2017 at 9:06
  • 2
    You are masking all your " inside raw and enclose it inside "", so it is a string. Commented Jun 13, 2017 at 9:06
  • Please, check your JSON string by any online validator. It seems that you have a problems in it ('a' and a closing bracket). And try then deserialize it by any deserializing tool. Commented Jun 13, 2017 at 10:01

3 Answers 3

3

You can use JSON.NET to convert your json to specific class

Official-site: http://www.newtonsoft.com/json

You can remove backslashes from json to let JObject interpret it.

public class Raw
{
    public Raw(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jRaw = jObject["raw"];
        Token = (string) jRaw["token"];
        queryName = (string) jRaw["queryName"];
        dataTestToSEND = (List<string>) jRaw["dataTestToSEND"];
        marketplace = (string) jRaw["Marketplace"]
        Region= jRaw["players"].ToArray();
    }

    public string Token {get;set;}
    public string queryName {get;set;}
    public List<string> dataTestToSEND {get;set}
    public string marketplace {get;set;}
    public string Region{get;set}



}

// Call User with your json
string json = @"{""body"":{""mode"":""raw"",""raw"":{""Token"":""123123"",""queryName"":""testMethod"",""dataTestToSEND"":{""IDs"":[""B00448MZUW"",""B071F7LBN6"",""B01BBZJZHQ""],""Marketplace"":""southAmerica"",""Region"":""West"",""PricingMethod"":""0""}}},""description"":""somedescriptionhere""}";
Raw raw = new Raw(json);
Sign up to request clarification or add additional context in comments.

5 Comments

If that json document would be the one from the question, then json2csharp would have generated more classes and no need for that kind of code
I have just used JObject Parse method to parse correct form of json to JObject
But you did not use the original json from the question with ..."raw": "{\"Token\" : \"123123\",... yours ..."raw":{"Token":"123123",... In original json raw property is of type string and in yours is of type object - That will make a huge difference
You can see what you get when using the original json string => dotnetfiddle.net/M20GJe
@SirRufo thanks for information. I have updated my answer
3

json2csharp converted your raw property to a string because it is not able to parse correctly JSON documents with escape characters. Remove the escape characters in order to let json2csharp create the right sharp class.

{"body":{"mode":"raw","raw":{"Token":"123123","queryName":"testMethod","dataTestToSEND":{"IDs":["B00448MZUW","B071F7LBN6","B01BBZJZHQ"],"Marketplace":"southAmerica","Region":"West","PricingMethod":0}}},"description":"somedescriptionhere"}

2 Comments

Please explain why a json document is not valid if a string property contains a string with a value that represents a json string? Are there any limitations of a json string property I never heard of?
You are right this is valid JSON. I meant this is not interpreted as valid JSON by json2csharp. I edited my answer. Thanks.
2

Build a custom converter to convert from a string property to a type

public class RawConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType != JsonToken.String)
        {
            throw new InvalidOperationException();
        }
        var value = (string)reader.Value;
        var obj = JsonConvert.DeserializeObject(value, objectType);
        return obj;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var str = JsonConvert.SerializeObject(value);
        writer.WriteValue(str);
    }
}

and put an attribute on the property where you need that converter

public class Body
{
    public string mode { get; set; }
    // This property is a raw string in the json document
    [JsonConverter(typeof(RawConverter))]
    public Data raw { get; set; }
}

public class RootObject
{
    public Body body { get; set; }
    public string description { get; set; }
}

public class Data
{
    public string Token { get; set; }
    public string queryName { get; set; }
    public DataTestToSEND dataTestToSEND { get; set; }
}

public class DataTestToSEND
{
    public string[] IDs { get; set; }
    public string Marketplace { get; set; }
    public string Region { get; set; }
    public int PricingMethod { get; set; }
}

and now you can deserialize the given json

{
  "body": {
    "mode": "raw",
    "raw": "{\"Token\":\"123123\",\"queryName\":\"testMethod\",\"dataTestToSEND\":{\"IDs\":[\"B00448MZUW\",\"B071F7LBN6\",\"B01BBZJZHQ\"],\"Marketplace\":\"southAmerica\",\"Region\":\"West\",\"PricingMethod\":0}}"
  },
  "description": "some description here"
}

with

var result = JsonConvert.DeserializeObject<RootObject>( jsonString );

Live example on .net fiddle with deserialization and serialization

1 Comment

I think you mean DeserializeObject<T> in var result = JsonConvert.SerializeObject<RootObject>( jsonString );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.