1

I have a Jobject.

{
  "address": "test",
  "state": "",
  "postcode": "",
  "membergroup": {
    "User1": false,
    "User2": false,
    "User3": false,
    "User4": true,
    "User5": false,
    "User6": true
  }
}

I am trying to get the membergroup property value for all true values in a list of string using c#.

like {"user4","user6"}

Is this possible? any suggestion of this please?

3
  • Where exactly is "I am trying" ? Show to us please. Commented Apr 15, 2016 at 10:00
  • What have you tried so far? You can deserialize all membergroup values into an array and pick the true values afterwards. Commented Apr 15, 2016 at 10:00
  • @ArthurRey .. i havent tried so far.. just checking is it possible or not? new to Json.net . yeah deserializing membergroup can do the job i think.i will check it. thanks Commented Apr 15, 2016 at 10:12

2 Answers 2

1

You can also use JObect if you don't want to have to create C# objects.

Note: Serializing this back to a json string in the first step is probably not needed depending on how you are getting your json. It should already be coming in as a json string.

using Newtonsoft.Json.Linq;



var json = JsonConvert.SerializeObject(yourObject);

var entireJson = JToken.Parse(json);
var propertyList = (JObject)entireJson["membergroup"];

foreach (var property in propertyList)
{
    var key = property.Key;
    var value = (bool)property.Value;

    if (value)
    {
        key.Dump();
    }
}

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

Comments

1

Using Json.NET :

Create a class that will represent your json in C#:

public class Entity
{
    [JsonProperty("address")]
    public string Address { get; set; }
    [JsonProperty("state")]
    public string State { get; set; }
    [JsonProperty("postcode")]
    public string PostCode { get; set; }
    [JsonProperty("membergroup")]
    public Dictionary<string, bool> MemberGroup { get; set; }
}

Get your json in a string, convert it to your c# class and pick only true values for your membergroup.

var entity = JsonConvert.DeserializeObject<Entity>(jsonString);
entity.MemberGroup = entity.MemberGroup.Where(x => x.Value).ToDictionary(k => k.Key, v => v.Value);

2 Comments

what is jsonString?i have a jobject do i need to convert/parse it to string ?
use jobject.ToString()

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.