2

I have an incoming JSON, which consists array of some objects, say, Foo. I deserialize them with

result = JsonConvert.DeserializeObject<List<Foo>>(message);

Now i want to add a string property to Foo, which will store it's JSON (which i received), so that Foo'll look like:

    public class Foo
{
    public int MyInt { get; set; }
    public bool MyBool { get; set; }
    public string JSON { get; set; }
}

But i don't know how can i say JSON.Net the way it can populate such a field..

UPD I'll clearify what i want. Say i receive JSON:

[{"MyInt":1,"MyBool":0},{"MyInt":2,"MyBool":0},{"MyInt":3,"MyBool":1}]

Here is array of 3 objects and i want, when deserializing, to add corresponding part of json to object, so that:

First object will contain {"MyInt":1,"MyBool":0}

Second object will contain {"MyInt":2,"MyBool":0}

Third object will contain {"MyInt":3,"MyBool":1}

in their JSON Property

I'll be gratefull for any help!

2
  • As you are deserialising to a List of Foo's, do you want a copy of the full JSON text in each instance of Foo? And are you intending to serialise the List of Foo's again? Commented Apr 1, 2015 at 14:19
  • @Ulric No, i want to add objects part of json to it's field. See my post edit for explanation Commented Apr 1, 2015 at 14:24

2 Answers 2

1

This is one way to do it, but it doesn't maintain the exact original JSON - but it does provide a static record of the original JSON (but without the exact format of the original values - i.e. Bool maybe be 0/1 or true/false):

var message = @"[{""MyInt"":1,""MyBool"":0},{""MyInt"":2,""MyBool"":0},{""MyInt"":3,""MyBool"":1}]";
var foos = JsonConvert.DeserializeObject<List<Foo>>(message);
var t = JsonConvert.SerializeObject(foos[0]);
foos = foos.Select(s => new Foo() { MyBool = s.MyBool, MyInt = s.MyInt, JSON = JsonConvert.SerializeObject(s) }).ToList();

If you are dealing with a lot of Foos, then you might want to find a more efficient way. There might be a way to 'update' using linq, rather than creating a new list.

Sign up to request clarification or add additional context in comments.

7 Comments

Brian suggested similar solution, i need exactly original JSON, not reserialized one
It will technically store the original JSON. If there's a problem with the JSON it won't deserialise - but if there isn't a problem, the re-serialised values will (for all intents and purposes) match. (The problem with Brian's suggestion is that changing the properties will change the JSON.) But if that is not 'accurate' enough, then NP :)
@Ulric It doesn't. See Fiddle. Notice the bool values in the original were 1 and 0 but in the output are true and false. Also notice the output includes the JSON member, which the original did not have.
@Brian Ah yes - you are correct. I hadn't noticed that before. >Filed away for future reference<
@Ulric Well, my problem still is that i can receive a very big JSON (i really can and many times), fail on an item, loose others (during to deserialization fail) and then i'll have to log whole JSON... Can i somehow "split" initial array to items and then parse them one-by-one?
|
0

Okay, i found an answer. I didn't know that i can deserialize message into JArray and then enumerate it (good job, newtonsoft:) ). Here is what i endede up with:

if (tokenType is JArray)
                {
                    var arr = JsonConvert.DeserializeObject(message) as JArray;
                    foreach (var item in arr)
                    {
                        try
                        {
                            var agentParameter = item.ToObject<Foo>();
                            agentParameter.JSON = item.ToString();
                            result.Add(agentParameter);
                        }
                        catch (Exception)
                        {
                            LogProvider.Error(string.Format("Failed to Deserialize message. Message text: \r\n {0}", item.ToString()));
                        }
                    }
                }

5 Comments

item.ToString() also re-serializes the object. It does not return the original JSON.
@BrianRogers that's a pitty, you're absolutely right:( Can i extract original JSON from JToken somehow?
I don't think so-- was just looking into that, but it appears that Json.Net does not hang onto the original JSON as it is parsed. As soon as it is converted into a value (or JToken) the original is discarded. You may need to look for a different parser.
@BrianRogers Brian, i tested my solution, when i paste some incorrect values into json items in array, ToObject throws exception and also, ToString returns original JSON. So i wrapped it with try-catch and now i have what i want. Thank you much for help!
No problem; I'm glad you were able to find a solution that works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.