Can't Resolve fromJson

不羁的心 提交于 2019-12-24 01:24:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!