如何在翻新中从JSON对象键中删除空格?

时间:2019-07-03 10:11:39

标签: java android json retrofit2 android-lifecycle

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

在哪里确切需要处理此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 "
    }]}

下面是我所做的代码,我被绞死在需要删除Poster空格的地方。

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;
    }
}

RetrofitService:

 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();
    }
}

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

@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();
    }

4 个答案:

答案 0 :(得分:2)

return this.http.get<any>(url);

这似乎无效,请参阅注释,因为修剪后的替代名称相同。

答案 1 :(得分:1)

尝试使用getter函数的好处

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

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

答案 2 :(得分:0)

将此代码用于您的项目:

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

答案 3 :(得分:0)

让我简化@JoopEggen的答案和评论。

当您应用两个字段时

 @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