I want to get a list of JSON objects with JSON from a API. For example affiliate.itunes
but with gson I can't go throw a jsonObject and i have to use java JSONObject and JSONArray class for this mater.
Is it possible to handle this completely with gson lib ?
This is json file that I copied into my android raw folder
and this is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
InputStream inputStream = getResources().openRawResource(R.raw.file);
String jsonStr = streamToString(inputStream);
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("results");
Type type = new TypeToken<List<BandJsonResult>>(){}.getType();
List<BandJsonResult> jsonResults = gson.fromJson(jsonArray.toString(),type);
for(int i = 0 ; i < jsonResults.size() ; i++){
Log.e("JSON " + i ,jsonResults.get(i).toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String streamToString(InputStream stream) {
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
}catch (IOException ex){
ex.printStackTrace();
}
return result.toString();
}
}
Gson uses reflection by default to (de-)serialize classes (unless you provide custom adapters), see also this example in the Gson user guide. Based on the screenshot you could add these two classes:
// You can give these classes any name
class ApiResponse {
// Uses the field names for (de-)serialization by default, but you can also
// specify custom names using #SerializedName
private int resultCount;
private List<BandResult> results;
}
class BandResult {
// You can also use enums and then either name the enum constants the same
// as the values, or annotate the enum constants with #SerializedName
private String wrapperType;
private String kind;
private int artistId;
...
}
And then use them when calling Gson.fromJson:
ApiResponse apiResponse = gson.fromJson(jsonStr, ApiResponse.class);
Related
I want to assign the JSONfile inside the Resources to a instance from JsonObject and parse it.
Please guide how?
MainActivicy:
boolean bool = true;
boolean bool2=true;
String s = "";
input = getResources().openRawResource(R.raw.infojson);
JsonReader reader = new JsonReader(new InputStreamReader(input));
reader.beginObject();
while (bool==true){
String sv ="";
sv=reader.nextName();
s +=sv;
if(sv.equals("id")| sv.equals("num")){
s +=" : " ;
s+=(String.valueOf(reader.nextInt()));
}
if (sv.equals("name")){
s +=" : " ;
s+=reader.nextString();
}
s+="\t";
bool = reader.hasNext();
}
JSON Content:
{
"id":"1","name":"E1","num":1111,
"My":{"id":"2","name":"E2","num":2222}
}
Create a model to parse your json like below:
class ResourseResponse {
private String id;
private String name;
private String num;
//getter-setter
}
Then parse your json from JsonReader and create your model.
JsonReader reader = new JsonReader(new InputStreamReader(input));
Gson gson = new Gson();
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
reader.beginArray();
while (reader.hasNext()) {
ResourseResponse response = gson.fromJson(reader, ResourseResponse.class);
//Add to list
}
reader.endArray();
} else {
ResourseResponse message = gson.fromJson(reader, ResourseResponse.class);
}
If the JSON content is not too big, you can easily create org.json.JSONObject and iterate its keys.
String jsonStr = "{\"id\":\"1\",\"name\":\"E1\",\"num\":1111, \"My\":{\"id\":\"2\",\"name\":\"E2\",\"num\":2222} }"
JSONObject json = new JSONObject(jsonStr);
json.keys().forEachRemaining(x -> {
System.out.println(x.toString());
try {
if (json.get(x.toString()) instanceof JSONObject) {
System.out.println(json.get(x.toString())); / here you can iterate the internal json object
}
} catch (JSONException e) {
e.printStackTrace();
}
});
Output is:
num
name
id
My
{"num":2222,"name":"E2","id":"2"}
I am sorry for I am a beginner.
I try to put the value into string name[], int age [], int hand[],
but all the value is null.
I don't know which part have problem. Since i learn this from youtube.
I just want to store the data to array.
Thank you
public class main extends AppCompatActivity {
String oName[] = new String [];
int oAge [] = new int [];
int oHand [] = new int [];
protected void onCreate(Bundle savedInstanceState) {...}
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground (String... values) {
InputStream is = null;
String result = ""; //Get json?
String line;
try {
URL ua = new URL("https://api.myjson.com/bins/r5kim"); //json address
HttpURLConnection conn = (HttpURLConnection) ua.openConnection();
conn.setRequestMethod("GET");
conn.connect();
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
JSONObject jo = new JSONObject(result); //get json
JSONArray op = jo.getJSONArray("opponents"); //json array?? parse??
for(int i = 0; i < op.length(); i++) {
oName[i] = op.getJSONObject(i).getString("name"); //Get null
oAge[i] = op.getJSONObject(i).getInt("age"); //Get null
oHand[i] = op.getJSONObject(i).getInt("hand"); //Get null
}
} catch (MalformedURLException e) { //exception
e.printStackTrace();
} catch (IOException e) { //exception
e.printStackTrace();
} catch (JSONException e) { //exception
e.printStackTrace();
}
return null;
}
}
Since you didn't post the json string it is hard to determinate what you are doing wrong.
The best advice I can give you is to check out gson library which is the most common json parser on Android (there are obv more, this is the one I use). how to add reference.
Watching videos, searching on google and also here on SO you will find thousands of "how to use gson posts", but anyway I will give you the fastest "how to" for it.
1. Assume you have a string like this:
{
"id":1,
"name":"Little Mouse"
}
2. Create an object matching the one passed by json string
public class MyObject{
private int id;
private String name;
//getters and setters
}
3. Now initialize gson and parse the string to the desired object
//Initialize Gson object with GsonBuilder (you can customize it, you will learn)
Gson gson = new GsonBuilder().create();
//parse your string using an object matching your output
MyObject myObject = gson.fromJson(myJsonString, MyObject.class);
It is pretty simple, but if you need help, ask freely
Post scriptum:
you can obiouvsly parse any kind of class, with also custom parameters and nested classes. You just have to create a model class with the parameters you need written with the same name (or you can explicit the desired name) and with the same property type (int, string, ...)
This is your model:
public class myJsonModel{
private List<Opponent> opponents;
//getters and setters
}
public class Opponent{
private String name;
private String age;
private String hand;
//getters and setters
}
So your result should be
myJsonModel myObject = gson.fromJson(myJsonString, myJsonModel.class);
i'm trying to do some work with methods of json in android.
i read the documentation of json and its methods but when i use them,they don't do what i expected they do.
public class getData_jason extends AsyncTask{
String KholaseKQuery;
String User;
public getData_jason(String link,String user) {
KholaseKQuery = link;
User = user;
}
#Override
protected String doInBackground(Object[] params) {
try{
URL mylink = new URL(KholaseKQuery);
URLConnection connect = mylink.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sB = new StringBuilder();
String eline;
while((eline = read.readLine())!= null)
{
sB.append(eline);
}
//MainActivity.jason_rs = sB.toString();
MainActivity.result = sB.toString();
MainActivity.is = true;
JSONObject jObj;
try{
jObj = new JSONObject(MainActivity.result.replace("callback(","")).getJSONObject("response");
JSONArray jsonArray = jObj.optJSONArray("Username");
for (int i = 0;i < jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getBoolean("ali")){
MainActivity.jason_rs = jsonObject.optString("Name");
//MainActivity.jason_rs = jsonObject.getString("Name");
}
}
}catch (Exception e){
}
}catch (Exception e){
/*Any Exception Here*/
}
return "";
}
}
when the process of reading from database is finished,in the result string is:
{"Username":["Name":"ali","Name":"hasan"]},{"Password":["aliali","hasanhasan"]}
so when i want to get ali name from the jsonObject,the value of jason_rs is null.
plz guid me what is that i don't know yet about using json or i do it wrong.
Your "json" is invalid. You can't have the same key more than once in a hash, on the other hand you also can't have keys (certainly not strings) in an array. You can validate it on http://jsonlint.com
I've got a little problem with parsing json into my android app.
This is how my json file looks like:
{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/
You can always use good old json.org lib. In your Java code :
First read your json file content into String;
Then parse it into JSONObject:
JSONObject myJson = new JSONObject(myJsonString);
// use myJson as needed, for example
String name = myJson.optString("name");
int profileIconId = myJson.optInt("profileIconId");
// etc
UPDATE 2018
After 5 years there is a new "standard" for parsing json on android. It's called moshi and one can consider it GSON 2.0. It's very similar but with design bugs fixed that are the first obstacles when you start using it.
https://github.com/square/moshi
First add it as a mvn dependency like this:
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>1.6.0</version>
</dependency>
After adding it we can use like so (taken from the examples):
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
More infos on their GitHub page :)
[old]
I would recommend using Gson.
Here are some links for tutorials:
how to convert java objecto from json format using GSON
Parse JSON file using GSON
Simple GSON example
Converting JSON data to Java object
An alternative to Gson you could use Jackson.
Jackson in 5 minutes
how to convert java object to and from json
This libraries basically parse your JSON to a Java class you specified.
to know if string is JSONArray or JSONObject
JSONArray String is like this
[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]
and this String as a JSONOject
{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
but how to call elements from JSONArray and JSONObject ?
JSNOObject info called like this
first fill object with data
JSONObject object = new JSONObject(
"{
\"internalName\": \"domin91\",
\"dataVersion\": 0,
\"name\": \"Domin91\",
\"profileIconId\": 578,
\"revisionId\": 0,
}"
);
now lets call information from object
String myusername = object.getString("internalName");
int dataVersion = object.getInt("dataVersion");
If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example
looping array
for ( int i = 0; i < jsonarray.length() ; i++)
{
//this object inside array you can do whatever you want
JSONObject object = jsonarray.getJSONObject(i);
}
if i know the object position inside JSONArray ill call it like this
//0 mean first object inside array
JSONObject object = jsonarray.getJSONObject(0);
This part do in onBackground in AsyncTask
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
result = json.getString("internalName");
data=json.getString("dataVersion");
ect..
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest you to use a library like gson as #jmeier wrote on his answer. But if you want to handle json with android's defaults, you can use something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}");
try {
MyObject myObject = new MyObject(s);
Log.d("MY_LOG", myObject.toString());
} catch (JSONException e) {
Log.d("MY_LOG", "ERROR:" + e.getMessage());
}
}
private static class MyObject {
private String internalName;
private int dataVersion;
private String name;
private int profileIconId;
private int revisionId;
public MyObject(String jsonAsString) throws JSONException {
this(new JSONObject(jsonAsString));
}
public MyObject(JSONObject jsonObject) throws JSONException {
this.internalName = (String) jsonObject.get("internalName");
this.dataVersion = (Integer) jsonObject.get("dataVersion");
this.name = (String) jsonObject.get("name");
this.profileIconId = (Integer) jsonObject.get("profileIconId");
this.revisionId = (Integer) jsonObject.get("revisionId");
}
#Override
public String toString() {
return "internalName=" + internalName +
"dataVersion=" + dataVersion +
"name=" + name +
"profileIconId=" + profileIconId +
"revisionId=" + revisionId;
}
}
}
Please checkout ig-json parser or Logan Square for fast and light JSON library.
For comparison, this is the stats from Logan Square developer.
Here you can parse any file from assets folder
fetch file from assets folder
public void loadFromAssets(){
try {
InputStream is = getAssets().open("yourfile.json");
readJsonStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
Convert JSON to your class object
public void readJsonStream(InputStream in) throws IOException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
int size = in.available();
Log.i("size", size + "");
reader.beginObject();
long starttime=System.currentTimeMillis();
while (reader.hasNext()) {
try {
Yourclass message = gson.fromJson(reader, Yourclass.class);
}
catch (Exception e){
Toast.makeText(this, e.getCause().toString(), Toast.LENGTH_SHORT).show();
}
}
reader.endObject();
long endtime=System.currentTimeMillis();
long diff=endtime-starttime;
int seconds= (int) (diff/1000);
Log.i("elapsed",seconds+"");
reader.close();
}
As the title says. I'd like to just use a JSON. Here is my code for what I'm guessing is my main activity. This grabs all the contents and places them in their respectful variables I'm hoping. Placed at the beginning:
public class WordDetailActivity extends FragmentActivity {
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null; {
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"wordlist.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String word = jsonObj.getString("word");
String dictionary = jsonObj.getString("dictionary");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
Now I have another file called WordContent.java that defines these variable again (a non edited version):
public static Map<String, WordItem> ITEM_MAP = new HashMap<String, WordItem>();
static {
// Add 3 sample items.
addItem(new WordItem("1", "This Word", "Blah blah blah"));
}
private static void addItem(WordItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
/**
* A dummy item representing a piece of content.
*/
public static class WordItem {
public String id;
public String word;
public String dictionary;
public WordItem(String id, String word, String dictionary) {
this.id = id;
this.word = word;
this.dictionary = dictionary;
}
#Override
public String toString() {
return word;
}
}
}
I haven't edited them yet because I have no idea where to go from here. Or rather how to put the contents of my JSON to the WordItem so they show up when I run the program. Another way to look at all of my code that is similar to this is to just create a Master/Detail Flow project in the Eclipse ADT bundle. I hope I'm saying all of this right. Let me know if there are more details I should shed. Very new to Android Dev but any pointer in the right direction is greatly appreciated.
Personally, I would do the JSON parsing in a separate file and probably use an AsyncTask. This is so you can decouple your files/classes as you really do not need an Activity for the parsing.
I tried to reuse as much of your code you posted above. With that being said, something like this should work or put you in the right direction:
public class ParseJsonTask extends AsyncTask<Void, Void, String> {
private Context mCtx;
public ParseJsonTask(Context ctx) {
this.mCtx = ctx;
}
#Override
protected String doInBackground(Void... params) {
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(mCtx.getAssets().open("wordlist.txt")));
String temp;
while ( (temp = br.readLine()) != null )
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.tostring();
}
#Override
protected void onPostExecute(Void jsonString) {
WordContent word = new WordContent(); // We use this oject to add the JSON data to WordItem
// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(jsonString);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String word = jsonObj.getString("word");
String dictionary = jsonObj.getString("dictionary");
// We can use the three variables above...
word.addItem(new WordItem(id, word, dictionary));
// or we can simply do...
// word.addItem(new WordItem(jsonObj.getInt("id"), jsonObj.getString("word"), jsonObj.getString("dictionary")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now whenever you want to parse the JSON file and use the class above you simply do the following:
ParseJsonTask task = new ParseJsonTask(getBaseContext());
task.execute();
Let me know if you have any questions...