问题
I've looked over this thread and this thread all trying to get android studio to recognize the fromJson method with no luck. I have com.google.code.gson:gson:2.6.2 as my gson dependency in my project structure. So, far all I've tried will still not allow this line to compile:
LookupRate cuRate = gson.fromJson(gson, LookupRate.class);
I've tried the following imports with no luck making my best effort to clean my project each time just for some kind of refresh. Imports:
import java.lang.reflect.Type;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.google.gson.reflect.TypeToken;
Should I be trying something else? I look over at what each of the two parameters should be dependent upon in google's documentation.
Here is some context for the gson variable as I realized it was late at night when I named some of this stuff. In the doInBackground() method I declared a variable gSB like so:
StringBuilder gSB = new StringBuilder();
inside of a try statement it assigned like so:
connectStat = (HttpURLConnection) params[0].openConnection();
InputStream inputer = new BufferedInputStream(connectStat.getInputStream());
scanner = new Scanner(inputer);
while (scanner.hasNext()) gSB.append(scanner.nextLine());
Log.v(checkRSP, "Response(" + connectStat.getResponseCode() + "):" +
connectStat.getResponseMessage());
All exceptions are handled properly then after my try,catch,finally. The variable gson is assigned like so:
String gson = gSB.toString();
Then the line where fromJson cannot be resolved comes next, but I will repeat it to remove any confusion my amateur description may have caused:
LookupRate cuRate = gson.fromJson(gson, LookupRate.class);
回答1:
the first parameter gson is not valid
one of the overloads -which i think you are trying to use- takes a String that contains the JSON content.
so your code should be:
//assume your JSON content is stored in variable name `myJsonStr`
LookupRate cuRate = gson.fromJson(myJsonStr, LookupRate.class);
you just need to fill myJsonStr form wherever you get your data (web-service, database,local file,...etc)
来源:https://stackoverflow.com/questions/36244619/cant-resolve-fromjson