Ebikeneser
Ebikeneser

Reputation: 2374

Cannot convert Array to String

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?

Upvotes: 1

Views: 8388

Answers (3)

Tarion
Tarion

Reputation: 17164

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

Upvotes: 0

Ebikeneser
Ebikeneser

Reputation: 2374

I sorted it -

string followers = (string)o["ids"].ToString();

Upvotes: 2

Darren
Darren

Reputation: 70766

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>

Upvotes: 0

Related Questions