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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Ebikeneser
  • 2,582
  • 13
  • 57
  • 111
  • I'm not sure I understand - is `SearchData` returning an `Array` and not a `String`? Where are you getting the exception? – David Hoerster May 02 '12 at 11:32
  • How is Ids(plural) going to be returned as a single string? – IAmGroot May 02 '12 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? – Ebikeneser May 02 '12 at 12:07

3 Answers3

2

I sorted it -

string followers = (string)o["ids"].ToString();
Ebikeneser
  • 2,582
  • 13
  • 57
  • 111
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>

Darren
  • 68,902
  • 24
  • 138
  • 144
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

Community
  • 1
  • 1
Tarion
  • 16,283
  • 13
  • 71
  • 107