简体   繁体   English

Android:将我从API返回的JSON转换为单个字符串

[英]Android: Get my returned JSON from an API into individual strings

I am trying to somehow get my returned JSON from an API into individual strings. 我试图以某种方式将我从API返回的JSON转换为单个字符串。

My code here gets information about a movie from the API: http://www.omdbapi.com/?t=Buffy&type=series&plot=short&apikey=8dc1b08d 我在这里的代码从API获取有关电影的信息: http : //www.omdbapi.com/?t= Buffy& type= series& plot= short& apikey=8dc1b08d

It returns the JSON. 它返回JSON。 However I need to get some value, such as "Buffy the Vampire Slayer" from the "Title" into a String variable. 但是,我需要获取一些值,例如将“标题”中的“吸血鬼猎人巴菲”转换为String变量。

News 新闻

package com.example.project21.stepbystep;

        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;

public class WalkNews extends AppCompatActivity implements AsyncResponse{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walk_news);

        Button btnGet = (Button) findViewById(R.id.btnGet);

        final GetMethod getRequest = new GetMethod(this);
        btnGet.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v)
            {
                getRequest.execute("http://www.omdbapi.com/?t=Buffy&type=series&plot=short&apikey=8dc1b08d");
            }
        });

    }

    public void processFinish(String output){

        TextView viewGet = (TextView) findViewById(R.id.txtGet);
        viewGet.setText(output);


    }
}

GetMethod 取得方法

package com.example.project21.stepbystep;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class GetMethod extends AsyncTask<String , Void ,String> {
    String server_response;
    private AsyncResponse delegate ;



    protected GetMethod(AsyncResponse delegate) {
        this.delegate = delegate;
    }

    @Override
    protected String doInBackground(String... strings) {


        delegate=delegate;
        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(strings[0]);

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            int responseCode = urlConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
                return server_response;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        // super.onPostExecute(s);
        delegate.processFinish(server_response);



    }


// Converting InputStream to String

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }
}

Async Response 异步响应

package com.example.project21.stepbystep;

public interface AsyncResponse {

    void processFinish(String output);
}

You should parse json string into map or pojo data model you can use android built in module JSONObject or you can use GSON open source library form google 您应该将json字符串解析为map或pojo数据模型,可以使用内置于模块JSONObject中的android,也可以使用Google的GSON开源库形式

https://github.com/google/gson https://github.com/google/gson

Create the Model class for the data you got from ApI like below: try this 为您从ApI获得的数据创建Model类,如下所示:

  public class DataObject {
        private String title;
        private String year;
        private String rated;
        private String genre;
        private String director;
        private String writer;
        private String actors;
        private String plot;
        private String language;
        private String country;
        private String awards;

        public String getTitle() {
            return title;
        }

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

        public String getYear() {
            return year;
        }

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

        public String getRated() {
            return rated;
        }

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

        public String getGenre() {
            return genre;
        }

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

        public String getDirector() {
            return director;
        }

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

        public String getWriter() {
            return writer;
        }

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

        public String getActors() {
            return actors;
        }

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

        public String getPlot() {
            return plot;
        }

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

        public String getLanguage() {
            return language;
        }

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

        public String getCountry() {
            return country;
        }

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

        public String getAwards() {
            return awards;
        }

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



         public DataObject processFinish(String output){
     TextView viewGet = (TextView) findViewById(R.id.txtGet);

            DataObject object = parseJson(output);
    if(object != null){
     viewGet.setText(object.getTitle);
    }
 }

 public DataObject parseJson(String output){
   DataObject dataObject = null;
   if(output != null){
   try {

      JSONObject jsonObject = new JSONObject(output);

      String title = jsonObject.getString("Title");
      String year = jsonObject.getString("Year");
      String rated = jsonObject.getString("Rated");
      dataObject = new DataObject();
      dataObject.setTitle(title);
      dataObject.setYear(year);
      dataObject.setRated(rated);
    } catch (Exception e) {
        e.printStackTrace();
     }
} else {
         Toast.makeText(context, "Didn't get data from json",Toast.LENGTH_SHORT).show();
}

            return dataObject;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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