【问题标题】:How to remove white space from json object key in retrofit?如何在改造中从 json 对象键中删除空格?
【发布时间】:2019-07-03 10:11:39
【问题描述】:

我有一个带有空格的字符串。如何在改造中去除空白。在下面的响应中,您可以看到“海报”和“海报”(有空格)

究竟需要在哪里处理这个 json 键来删除改造中的空格?

{
    "movies": [{
        "Title": "TheAvengers ",
        "Year": "2012 ",
        "Rated": "PG-13 ",
        "Genre": "Action, Adventure, Sci-Fi ",
        "Actors": "Robert Downey Jr., Chris Evans, Mark Ruffalo, Chris Hemsworth ",
        "Plot": "Earth's mightiest heroes must come together and learn to fight as a team if they are going to stop the mischievous Loki and his alien army from enslaving humanity. ",
        "Language": "English, Russian, Hindi ",
        "Country": "USA ",
        "Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg ",
        "Released": "04 May 2012 ",
        "Runtime": "143 min ",
        "Director": "Joss Whedon ",
        "Writer": "Joss Whedon (screenplay), Zak Penn (story), Joss Whedon (story) ",
        "Awards": "Nominated for 1 Oscar. Another 38 wins \u0026 79 nominations. "
    }, {
        "Title": "Sleepless ",
        "Year": "2017 ",
        "Rated": "R ",
        "Released": "13Jan 2017 ",
        "Runtime": "95 min ",
        "Genre": "Action, Crime, Thriller ",
        "Director": "Baran bo Odar ",
        "Writer": "Andrea Berloff (screenplay by), Frédéric Jardin (based on the film    Nuit blanche written by), Nicolas Saada (based on the film Nuit blanche written by), Olivier Douyère (based on the film    Nuit blanche   written by)",
        "Actors": "Jamie Foxx, Michelle Monaghan, Scoot McNairy, Dermot Mulroney ",
        "Plot": "A cop with a connection to the criminal underworld scours a nightclub in search of his kidnapped son. ",
        "Language": "English ",
        "Country": "USA ",
        "Awards": "1 nomination. ",
        "Poster ": "https://m.media-amazon.com/images/M/MV5BNjEwMDAyOTM4OV5BMl5BanBnXkFtZTgwMzc4MjMyMDI@._V1_SX300.jpg "
    }]}

下面是我所做的代码,我在需要删除海报空白的地方被绞死了。

Pojo 类:

public class Movies implements Serializable {
    @SerializedName("Title")
    private String Title;
    @SerializedName("Year")
    private String Year;
    @SerializedName("Rated")
    private String Rated;
    @SerializedName("Released")
    private String Released;
    @SerializedName("Runtime")
    private String Runtime;
    @SerializedName("Genre")
    private String Genre;
    @SerializedName("Director")
    private String Director;
    @SerializedName("Writer")
    private String Writer;
    @SerializedName("Actors")
    private String Actors;
    @SerializedName("Plot")
    private String Plot;
    @SerializedName("Language")
    private String Language;
    @SerializedName("Country")
    private String Country;
    @SerializedName("Awards")
    private String Awards;
    @SerializedName("Poster")
    private String Poster;


    // Getter Methods

    public String getTitle() {
        return Title;
    }

    public String getYear() {
        return Year;
    }

    public String getRated() {
        return Rated;
    }

    public String getReleased() {
        return Released;
    }

    public String getRuntime() {
        return Runtime;
    }

    public String getGenre() {
        return Genre;
    }

    public String getDirector() {
        return Director;
    }

    public String getWriter() {
        return Writer;
    }

    public String getActors() {
        return Actors;
    }

    public String getPlot() {
        return Plot;
    }

    public String getLanguage() {
        return Language;
    }

    public String getCountry() {
        return Country;
    }

    public String getAwards() {
        return Awards;
    }

    public String getPoster() {
        return Poster == null ? Uri.parse("R.drawable.ic_launcher_background").toString() : Poster;
    }

    // Setter Methods

    public void setTitle(String Title) {
        this.Title = Title;
    }

    public void setYear(String Year) {
        this.Year = Year;
    }

    public void setRated(String Rated) {
        this.Rated = Rated;
    }

    public void setReleased(String Released) {
        this.Released = Released;
    }

    public void setRuntime(String Runtime) {
        this.Runtime = Runtime;
    }

    public void setGenre(String Genre) {
        this.Genre = Genre;
    }

    public void setDirector(String Director) {
        this.Director = Director;
    }

    public void setWriter(String Writer) {
        this.Writer = Writer;
    }

    public void setActors(String Actors) {
        this.Actors = Actors;
    }

    public void setPlot(String Plot) {
        this.Plot = Plot;
    }

    public void setLanguage(String Language) {
        this.Language = Language;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public void setAwards(String Awards) {
        this.Awards = Awards;
    }

    public void setPoster(String Poster) {
        this.Poster = Poster;
    }
}

电影回复:

public class MovieResponse implements Serializable {
    @SerializedName("movies")
    private List<Movies> movies;

    public List<Movies> getMovies() {
        return movies;
    }

    public void setMovies(List<Movies> movies) {
        this.movies = movies;
    }
}

改造服务:

 public class RetrofitService {
    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.myjson.com/bins/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    public static <S> S cteateService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);
    }
}

MoviesRepository:(这里是我处理响应的地方)

    public class MoviesRepository {
        private static MoviesRepository moviesRepository;
        private MovieApiInterface newsApi;
        public static Application application;

        public static MoviesRepository getInstance() {
            if (moviesRepository == null) {
                moviesRepository = new MoviesRepository(application);
            }
            return moviesRepository;
        }
  public MoviesRepository(Application application) {
        this.application = application;
        newsApi = RetrofitService.cteateService(MovieApiInterface.class);
    }

    public MutableLiveData<MovieResponse> getMovieUpdates() {
        final MutableLiveData<MovieResponse> moviesData = new MutableLiveData<>();
        newsApi.getMovieDetails().enqueue(new Callback<MovieResponse>() {
            @Override
            public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
                GsonBuilder builder = new GsonBuilder();
                Gson mGson = builder.create();
                if (response.isSuccessful()) {
                    if(response.body()!=null) {
                        moviesData.setValue(response.body());
                    }
                }

            }

            @Override
            public void onFailure(Call<MovieResponse> call, Throwable t) {
                Log.i("RETROFIT RESPONSE", "Failure"+call.toString());
                Log.i("RETROFIT RESPONSE", "Failure"+t);
               // moviesData.setValue(null);

            }
        });
        return moviesData;
    }



      public interface MovieApiInterface {
        @GET("9xqev")
        Call<MovieResponse> getMovieDetails();
    }

我不知道我需要通过从 gson.FromJson 转换来更改海报密钥字符串来检查的地方。其中有空格。

我使用了 MVVM,我得到的所有数据除了带有空格的海报。

public class MoviesViewModel extends AndroidViewModel {
    private MutableLiveData<MovieResponse> mutableLiveData;
    private MoviesRepository moviesRepository;

    public MoviesViewModel(@NonNull Application application) {
        super(application);
        moviesRepository = new MoviesRepository(application);
    }

    public void init() {
        if (mutableLiveData != null) {
            return;
        }
        moviesRepository = MoviesRepository.getInstance();
        mutableLiveData = moviesRepository.getMovieUpdates();
    }

    public MutableLiveData<MovieResponse> getNewsRepository() {
        return moviesRepository.getMovieUpdates();
    }
}

我尝试的其他方法是: 失败案例一:
我无法在 Serializable 中放置两个带有空格的海报

@SerializedName("Poster")
    private String Poster;

@SerializedName("Poster ") // with whitespace.
    private String Poster;

失败案例 2:(使用修剪,但这仅反映值而不反映键)

public String getPoster() {
        return Poster == null ? Uri.parse("R.drawable.ic_launcher_background").toString() : Poster.trim();
    }

【问题讨论】:

    标签: java android json retrofit2 android-lifecycle


    【解决方案1】:
    @SerializedName(value="Poster", alternate={"Poster ", "Pöster"})
    String poster;
    

    这似乎不起作用,请参阅评论,因为修剪过的替代品会给出相同的名称。

    【讨论】:

    • 我使用了这个,但我遇到了崩溃,原因是:java.lang.IllegalArgumentException: class movie..demo.DataModel.Movies 声明了多个名为 Poster 的 JSON 字段
    • 只是alternate="Poster "?所以它似乎在内部不起作用。对不起。
    • 是否有其他替代解决方案。我尝试了很多方法,但仍然无法找到并坚持下去。 @Joop Eggen
    • @Star 对不起,似乎必须链接一些转换器,简单地对键进行文本修剪。不知道改造。
    • 好的,没问题。 @乔普
    【解决方案2】:

    让我从@JoopEggen 的答案和 cmets 中简化。

    当你应用两个字段时

     @SerializedName(value="Poster", alternate={"Poster ", "Pöster"})
      String poster;
    

    它抛出“你不能声明多个名为 Poster 的 JSON 字段”

    那么解决方案是什么,

    //assign a dummy json field as images and replace with poster
    
    @SerializedName(value = "Images", alternate = {"Poster"}) //no whitespace
        private String Images;
    
    
    @SerializedName("Poster ") //with white space
        private String Poster;
    

    在 getter setter 的适配器中处理这两个图像。

       String poster= movies.get(position).getPoster(); //Poster with whitespace
        String image = movies.get(position).getImages(); //Poster without whitespace
    

    【讨论】:

      【解决方案3】:

      尝试使用getter函数的好处

      public String getTitle() {
              return Title.trim();
          }
      

      和其他人一样。尝试使用这个,如果这不能帮助在评论中让我知道,我们会找到另一个解决方案

      【讨论】:

      • 我试过了,但这只修复了值而不是键。
      • 我也试过这种方式。公共字符串 getPoster() { 返回海报 == null ? Uri.parse("R.drawable.ic_launcher_background").toString() : Poster.trim(); }
      • 为什么需要它来修剪键,值不是键有用。有什么具体的吗?
      • 我使用了 Title.trim,但在尝试在空对象引用上调用虚拟方法 'java.lang.String java.lang.String.trim()' 时出现错误
      • 没有。实际上我需要从海报访问网址,但它有两个不同的海报,这就是问题所在。
      【解决方案4】:

      在您的项目中使用此代码:

      String strRemoveSpace= getPoster().toString().replaceAll("\\s", ""); // using built in method  
      System.out.println(strRemoveSpace);  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 2014-09-06
        • 2015-10-08
        • 1970-01-01
        相关资源
        最近更新 更多