1

I am using the following WebMethod-

[WebMethod]
    public string get_IDs(string uid)
    {


        string url = "www.foobar.com/id=-1&user_id=" + uid";

        String data = SearchData(url);

        JObject o = JObject.Parse(data);

        string ids = (string)o["ids"];


        return ids;
    }

My problem being the data returned is in array form, I want it back as a string however this throws up the exception that cannont convert array to string. How can I do this?

3
  • I'm not sure I understand - is SearchData returning an Array and not a String? Where are you getting the exception? Commented May 2, 2012 at 11:32
  • How is Ids(plural) going to be returned as a single string? Commented May 2, 2012 at 11:49
  • @David Hoerster yes SearchData is bringing back a JSON withihn that JSONI am trying to get ids which are in an array. I am trying to return this as a string however cannot convert it to a string? Commented May 2, 2012 at 12:07

3 Answers 3

2

I sorted it -

string followers = (string)o["ids"].ToString();
Sign up to request clarification or add additional context in comments.

Comments

0

Can you not do o["ids"].ToString(); ??

I am unfamiliar with the JObject class, so if that does not have a ToArray function and if you are expecting more than 1 ID via JObject o variable you could try:

public List<string> get_IDs(string uid)
{


    string url = "www.foobar.com/id=-1&user_id=" + uid";

    String data = SearchData(url);

    JObject o = JObject.Parse(data);

    List<string> ids = new List<string>();

    foreach (obj in o) {
       ids.add(obj.ToString());
    } 
    return ids;

}

Notice the method type has from string to List<string>

Comments

0

You can use

string result = string.Join(";", array);
return result;

What is the type of o["ids"]?

var ids = (string)o["ids"];
console.WriteLine(ids.GetType());

If ids is of type int[] you have to cast all elements to String. See: C# Cast Entire Array?

var strIds = Array.ConvertAll(ids, item => (String)item);
string result = string.Join(";", strIds);
return result;

If ids is an JObject you can use the ffollowing function of JObject:

public override IEnumerable<T> Values<T>()

IEnumerable<String> strIds = ids.Values<String>();

And Convert the Enumerable into a single String if needed: C# IEnumerable<Object> to string

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.