3

How can I parse the elements of an array in a Json string using DataContractJsonSerializer? The syntax is:

{
   "array":[
 {
  "elementsProperies":"SomeLiteral"
 }
 ]
}

2 Answers 2

2

You wouldn't necessarily "parse" a json string using DataContractJsonSerializer, but you can deserialize it into an object or list of objects using this. Here is a simple way to deserialize it to a list of objects if this is what you're after.

First you need to have an object type you plan on deserializing to:

[DataContract]
public class MyElement
{
    [DataMember(Name="elementsProperties")] // this must match the json property name
    public string ElementsProperties { get; set; }
}

You can then use something like the following method to deserialize your json string to a list of objects

private List<MyElement> ReadToObject(string json)
{
    var deserializedElements = new List<MyElement>();
    using(var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
        var ser = new DataContractJsonSerializer(deserializedElements.GetType());
        deserializedElements = ser.ReadObject(ms) as List<MyElement>;
    }
    return deserializedUsers;
}
Sign up to request clarification or add additional context in comments.

2 Comments

you can also look into other json deserializers like json.net
thanks a bunch =D I already found the "solution" though. ( and idd, I used the deserialize method =3 ) What I did, with my retard head, is giving both the List in which to store the data, and also the element that I wanted to store the [DataContract] prefix. ( I started with just the element but only later decided to use a List to store data, and forgot about the [DataContract]. I'm sorry, but forgot to delete the question. ( should I, or should I keep it for future reference? )
0

I suggest using Json.net.

In it you would just call:

var jsonObj = JObject.Parse(yourjsonstring);

var elPropertyValue = (string)jsonObj.SelectToken("array[0].elementsProperies");

to get the "SomeLiteral".

Comments

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.