Reputation: 331
I have a json response where i am able to reach through into a single node at this point. I am not able to loop through the response to fetch a particular value i.e. 'PropertyValue' and store it in a list.
Here is the response and the code:
{
"documents":[
{
"document":[
{
"propertyname":"Id",
"propertyvalue":"{1ED8A008-959D-4D54-9B3D-48F10F5CED85}"
},
{
"propertyname":"DVALinkedDocId",
"propertyvalue":""
},
{
"propertyname":"DVAPageNumber",
"propertyvalue":""
}
]
},
{
"document":[
{
"propertyname":"Id",
"propertyvalue":"{FCDACA2E-98BD-4E7F-BB4B-F1A543B40E3A}"
},
{
"propertyname":"DVALinkedDocId",
"propertyvalue":""
},
{
"propertyname":"DVAPageNumber",
"propertyvalue":""
}
]
},
{
"document":[
{
"propertyname":"Id",
"propertyvalue":"{3DC1C70F-35AE-43AA-8CEC-FACE3ACEA519}"
},
{
"propertyname":"DVALinkedDocId",
"propertyvalue":""
},
{
"propertyname":"DVAPageNumber",
"propertyvalue":""
}
]
},
{
"document":[
{
"propertyname":"Id",
"propertyvalue":"{B397323D-C0D4-4DA2-A95A-A79C3842D2DE}"
},
{
"propertyname":"DVALinkedDocId",
"propertyvalue":""
},
{
"propertyname":"DVAPageNumber",
"propertyvalue":""
}
]
}
]
}
Here is my code:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GuidResponse));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseData)))
{
var response = (GuidResponse)serializer.ReadObject(ms);
foreach (var obj in response.documents)
{
foreach (var docObj in obj.document)
{
string Guid = docObj.propertyvalue;
}
}
}
The Problem is i want to show all the guid property values in a list but i am not able to do that with the above code.
Upvotes: 3
Views: 5378
Reputation: 3726
Alternatively you can use JSON.Net -
public class Document2
{
public string propertyname { get; set; }
public string propertyvalue { get; set; }
}
public class Document
{
public List<Document2> document { get; set; }
}
public class RootObject
{
public List<Document> documents { get; set; }
}
And then -
var o = JsonConvert.DeserializeObject<RootObject>(new StreamReader("json").ReadToEnd());
var list = new List<string>();
foreach (var item in o.documents)
{
list.Add(item.document[0].propertyvalue);
}
Upvotes: 0
Reputation: 331
This worked for me:
var list = response.documents.SelectMany(d => d.document).Select(o => o.propertyvalue).Where(r => !string.IsNullOrEmpty(r)).ToList();
Upvotes: 0
Reputation: 2204
Create a string type array or list that holds all object you are passing to c# program through Json. Create a model class in C# and dis serialize data to that model.
string[] AchievementsList = Regex.Matches(strAchievements, @"\{.*?\}").Cast<Match>().Select(m => m.Value).ToArray();
for (i = 0; i < AchievementsList.Length; i++)
{
TestClass aJson = js.Deserialize<TestClass>(AchievementsList[i]); //use aJson object to access properties you need
}
Class for holding object of json type
class TestClass
{
public string Name { get; set; }
}
Upvotes: 1