如何获取JSON响应的特定字段?

时间:2019-12-05 22:36:30

标签: android android-studio kotlin

我在https://jsonstorage.net/api/items/0b0609e3-9d83-487f-b2e8-5ffdfae4723b上有一个托管的json文件,它可以作为响应:

[
  {
    "name":"Drop Biscuits and Sausage Gravy",
    "ingredients":"Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\n1-1/2 stick (3/4 Cup) Cold Butter, Cut Into Pieces\n1-1/4 cup Butermilk\n SAUSAGE GRAVY\n1 pound Breakfast Sausage, Hot Or Mild\n1/3 cup All-purpose Flour\n4 cups Whole Milk\n1/2 teaspoon Seasoned Salt\n2 teaspoons Black Pepper, More To Taste",
    "url":"http://thepioneerwoman.com/cooking/2013/03/drop-biscuits-and-sausage-gravy/",
    "image":"http://static.thepioneerwoman.com/cooking/files/2013/03/bisgrav.jpg",
    "ts":{
      "$date":1365276011104
    },
    "cookTime":"PT30M",
    "source":"thepioneerwoman",
    "recipeYield":"12",
    "datePublished":"2013-03-11",
    "prepTime":"PT10M",
    "description":"Late Saturday afternoon, after Marlboro Man had returned home with the soccer-playing girls, and I had returned home with the..."
  },
  {
    "name":"Hot Roast Beef Sandwiches",
    "ingredients":"12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)\n1 pound Thinly Shaved Roast Beef Or Ham (or Both!)\n1 pound Cheese (Provolone, Swiss, Mozzarella, Even Cheez Whiz!)\n1/4 cup Mayonnaise\n3 Tablespoons Grated Onion (or 1 Tbsp Dried Onion Flakes))\n1 Tablespoon Poppy Seeds\n1 Tablespoon Spicy Mustard\n1 Tablespoon Horseradish Mayo Or Straight Prepared Horseradish\n Dash Of Worcestershire\n Optional Dressing Ingredients: Sriracha, Hot Sauce, Dried Onion Flakes Instead Of Fresh, Garlic Powder, Pepper, Etc.)",
    "url":"http://thepioneerwoman.com/cooking/2013/03/hot-roast-beef-sandwiches/",
    "image":"http://static.thepioneerwoman.com/cooking/files/2013/03/sandwiches.jpg",
    "ts":{
      "$date":1365276013902
    },
    "cookTime":"PT20M",
    "source":"thepioneerwoman",
    "recipeYield":"12",
    "datePublished":"2013-03-13",
    "prepTime":"PT20M",
    "description":"When I was growing up, I participated in my Episcopal church's youth group, and I have lots of memories of weekly meetings wh..."
  }
]

我正在使用以下代码:

JSONPlaceHolderApi.kt

interface JSONPlaceHolderApi {


    @GET("https://jsonstorage.net/api/items/0b0609e3-9d83-487f-b2e8-5ffdfae4723b ") 
    fun getAll() : Call<List<DataModel>>
    @POST("https://jsonstorage.net/api/items/0b0609e3-9d83-487f-b2e8-5ffdfae4723b ")
    @FormUrlEncoded
    fun getName(@Field("name")  name : String) : Call<List<DataModel>>

}

MainActivity.kt

 private fun fetchAllNames(name :  String) {


        val client = RestUtil.instance.retrofit.create(JSONPlaceHolderApi::class.java)
        val call = client.getName(name)
        call.enqueue(object : Callback<List<DataModel>> {
            override fun onResponse(call: Call<List<DataModel>>, response: Response<List<DataModel>>) {
                if (response.body() != null) {

                    val recepts = response.body()
                    var stringBuilder = StringBuilder("")
                    recepts?.forEach {
                        stringBuilder.append(it.name)
                        stringBuilder.append("")
                        stringBuilder.append(it.ingredients)
                        stringBuilder.append("\n")
                    }

                    receptsName.text = stringBuilder.toString()
                    Log.d("receptname",stringBuilder.toString())

                }
            }
            override fun onFailure(call: Call<List<DataModel>>, t: Throwable) {
                t.printStackTrace()
            }
        })
    }

我正在尝试创建一种方法,在该方法中我会说getIngredients(name:String),在其中键入名称并从该名称获取成分。因此,在这种情况下,它将返回如下内容:

"ingredients":"Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\n1-1/2 stick (3/4 Cup) Cold Butter, Cut Into Pieces\n1-1/4 cup Butermilk\n SAUSAGE GRAVY\n1 pound Breakfast Sausage, Hot Or Mild\n1/3 cup All-purpose Flour\n4 cups Whole Milk\n1/2 teaspoon Seasoned Salt\n2 teaspoons Black Pepper, More To Taste"

1 个答案:

答案 0 :(得分:0)

为了解析JSON,请查看以下网站:https://app.quicktype.io/

只需使用此类即可将JSON解析为对象:

https://app.quicktype.io/

    // Converter.java

// To use this code, add the following Maven dependency to your project:
//
//     com.fasterxml.jackson.core : jackson-databind : 2.9.0
//
// Import this package:
//
//     import io.quicktype.Converter;
//
// Then you can deserialize a JSON string with
//
//     ExampleStackOverflow[] data = Converter.fromJsonString(jsonString);

package io.quicktype;

import java.util.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.JsonProcessingException;

public class Converter {
    // Serialize/deserialize helpers

    public static ExampleStackOverflow[] fromJsonString(String json) throws IOException {
        return getObjectReader().readValue(json);
    }

    public static String toJsonString(ExampleStackOverflow[] obj) throws JsonProcessingException {
        return getObjectWriter().writeValueAsString(obj);
    }

    private static ObjectReader reader;
    private static ObjectWriter writer;

    private static void instantiateMapper() {
        ObjectMapper mapper = new ObjectMapper();
        reader = mapper.reader(ExampleStackOverflow[].class);
        writer = mapper.writerFor(ExampleStackOverflow[].class);
    }

    private static ObjectReader getObjectReader() {
        if (reader == null) instantiateMapper();
        return reader;
    }

    private static ObjectWriter getObjectWriter() {
        if (writer == null) instantiateMapper();
        return writer;
    }
}

// ExampleStackOverflow.java

package io.quicktype;

import java.util.*;
import com.fasterxml.jackson.annotation.*;

public class ExampleStackOverflow {
    private String name;
    private String ingredients;
    private String url;
    private String image;
    private Ts ts;
    private String cookTime;
    private String source;
    private String recipeYield;
    private String datePublished;
    private String prepTime;
    private String description;

    @JsonProperty("name")
    public String getName() { return name; }
    @JsonProperty("name")
    public void setName(String value) { this.name = value; }

    @JsonProperty("ingredients")
    public String getIngredients() { return ingredients; }
    @JsonProperty("ingredients")
    public void setIngredients(String value) { this.ingredients = value; }

    @JsonProperty("url")
    public String getURL() { return url; }
    @JsonProperty("url")
    public void setURL(String value) { this.url = value; }

    @JsonProperty("image")
    public String getImage() { return image; }
    @JsonProperty("image")
    public void setImage(String value) { this.image = value; }

    @JsonProperty("ts")
    public Ts getTs() { return ts; }
    @JsonProperty("ts")
    public void setTs(Ts value) { this.ts = value; }

    @JsonProperty("cookTime")
    public String getCookTime() { return cookTime; }
    @JsonProperty("cookTime")
    public void setCookTime(String value) { this.cookTime = value; }

    @JsonProperty("source")
    public String getSource() { return source; }
    @JsonProperty("source")
    public void setSource(String value) { this.source = value; }

    @JsonProperty("recipeYield")
    public String getRecipeYield() { return recipeYield; }
    @JsonProperty("recipeYield")
    public void setRecipeYield(String value) { this.recipeYield = value; }

    @JsonProperty("datePublished")
    public String getDatePublished() { return datePublished; }
    @JsonProperty("datePublished")
    public void setDatePublished(String value) { this.datePublished = value; }

    @JsonProperty("prepTime")
    public String getPrepTime() { return prepTime; }
    @JsonProperty("prepTime")
    public void setPrepTime(String value) { this.prepTime = value; }

    @JsonProperty("description")
    public String getDescription() { return description; }
    @JsonProperty("description")
    public void setDescription(String value) { this.description = value; }
}

// Ts.java

package io.quicktype;

import java.util.*;
import com.fasterxml.jackson.annotation.*;

public class Ts {
    private long date;

    @JsonProperty("$date")
    public long getDate() { return date; }
    @JsonProperty("$date")
    public void setDate(long value) { this.date = value; }
}

导入类后,请使用此
       // ExampleStackOverflow [] data = Converter.fromJsonString(jsonString);

解析您的JSON。

现在您有了一个普通的Java对象,您可以像在Java中一样在其中选择所需的任何字段