简体   繁体   中英

How to get a specific string between a string that are inside another string?

I got a problem that are like this:

{ 
  "animal_zone":[
    {
      "id":0001
    },
    {
      "id":0002
    }
  ]
}

That is an API that I get from a website (sorry I can't tell the link), what I want from that chunk of text is to just get the category and the id string, is it possible to do so without doing regex? (I'm really bad at it)

Output example that I need (inside an array of string[]):

animal_zone
0001
0002

What I have tried:

private void MClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e){
   string webResult = Encoding.UTF8.GetString(e.Result);
   int goFrom = webResult.IndexOf("\"animal_zone\": [") + "\"animal_zone\": [".Length;
   int goTo = webResult.IndexOf("]");
   string pveResult = webResult.Substring(goFrom, goTo - goFrom);
}

That code get me the text between " "animal_zone": " and " ] ":

{
  "id":0001
},
{
  "id":0002
}

But I still don't know how to get the 0001 and 0002 together inside an array of string[]

Or is there better way to get an information from the API website instead of doing it by getting all of the text and substring/split it one by one?

Please help me. Thank you

You should create class (use json2sharp if you don't know how should look class ):

public class AnimalZone
{
    public int id { get; set; }
}

and use JSON.NET

List<AnimalZone> idList= JsonConvert.DeserializeObject<List<AnimalZone>>(yourJson);

This is common stuff, just use a library. This format is called JSON by the way. http://www.newtonsoft.com/json

What you want to do is make a native c# class you can use to map this into:

 public class AnimalStuff
    {
        public List<Ids> animal_zone { get; set; }
    }

    public class Ids
    {
        public int Id { get; set; }
    }

I mean, the example is there at the top of the page but anyway:

  AnimalStuff animalstuff = JsonConvert.DeserializeObject<AnimalStuff>(yourJsonString);

  string[] answer = { "animal_zone" };
  answer.Concat(animalstuff.animal_zone.Select(a=>a.ToString()));

That's the general idea.

here a fully working code example

the POCO

 public class AnimalZone
    {
        public int id { get; set; }
    }

    public class AnimalZones
    {
        public List<AnimalZone> animal_zone { get; set; }
    }

how you can deserialize it

var  animals= JsonConvert.DeserializeObject<AnimalZones>(txt);

then use LINQ to select your zones

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM