Parsing JSON correctly in Android Studio? - java

Alright, totally new to Android Studio, but I've been trying to parse backpack.tf's json in Android Studio, and I'm a bit stuck.
Here is a little snippet of json I would try to parse:
{
"response": {
"success": 1,
"current_time": 1448658000,
"items": {
"A Color Similar to Slate": {
"last_updated": 1448654419,
"quantity": 48,
"value": 99
},
And the code I'm using to parse JSON is here:
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("A Color Similar to Slate");
JSONObject finalObject = parentArray.getJSONObject(3);
int price = finalObject.getInt("value");
return "$" + price;
Thanks a bunch!

Try this:
You have JSON:
{"response":{
"success": 1,
"current_time": 1448658000,
"items": {
"A Color Similar to Slate": {
"last_updated": 1448654419,
"quantity": 48,
"value": 99
},
}
}
}
Code:
String finalJSON =buffer.toString();;
JSONObject parentObject = null;
try {
parentObject = new JSONObject(finalJSON);
JSONObject objectA_Color=parentObject.getJSONObject("response").getJSONObject("items").getJSONObject("A Color Similar to Slate");
int value=objectA_Color.getInt("value");
} catch (JSONException e) {
e.printStackTrace();
}

1) Create some (custom, adjusted to your needs) Model class
public class Model {
private String title;
private List<String> authors;
//getters fields, magic ...
}
2) Parse your JSON (
public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Model model = gson.fromJson(br, Model.class);
OR
1) Parse it with JSON Parser
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(br).getAsJsonObject();
Both ways Require GSON library https://github.com/google/gson

Related

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

How to use gson for getstring of json?

I am new to use gson.
I found a lots of tutorial there I can learn of gson but there are using recylerview and model file.
JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG , String.valueOf(response));
try {
String statusObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusObject.equals("200")) {
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject managerResponse= jsonArray.getJSONObject(i);
// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
Here I can get data from jsonrequest using volley but unable to do that same process using volley and gson. Is there any way to use gson?
Thank You.
Update
My JSON Response
{
"status": "200",
"msg": "Successfully",
"response": [
{
"user_id": "1",
"name": "HEMANT OJHA",
"email": "hemguna#gmail.com",
"mobile": "9584919991",
"address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
"user": "admin",
"api_token": "admin"
}
]
}
Generating POJO class from JSON
// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above
{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
"key": "Value"
},
{
"key": "Value"
}
]
}
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("keyOne")
#Expose
private int keyOne;
#SerializedName("keyTwo")
#Expose
private String keyTwo;
#SerializedName("someArray")
#Expose
private List<SomeArray> someArray = null;
public int getKeyOne() {
return keyOne;
}
public void setKeyOne(int keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
public List<SomeArray> getSomeArray() {
return someArray;
}
public void setSomeArray(List<SomeArray> someArray) {
this.someArray = someArray;
}
}
// Parsing JSON response with GSON
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
int keyOneValue = resultObj.getKeyOne() // First JSON Object
// Getting String value
String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object
List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents
// Depending on JSON response that you've updated in your question
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
String status = resultObj.getStatus();
String msg = resultObj.getMsg();
List<Response> responseList = resultObj.getResponse();
The best way to use for entire app is create a Utils class and use it for conversion.
GsonUtils.java
// This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {
private static final Gson gson = new Gson();
// This will Convert Java Objects into JSON String...
public static String toGson(Object object) {
return gson.toJson(object);
}
// Gives Java Objects from JSON
public static <T> T fromGson(String json, Class<T> type) {
return gson.fromJson(json, type);
}
public static JsonArray fromGson(String json) {
return new JsonParser().parse(json).getAsJsonArray();
}
}
Now convert any json to and from POJO via,
POJO pojoObj = GsonUtils.toGson(POJO.class);
Try this
JSON response
String str = new Gson().toJson(response)

Parse JSON Objects and store them in to an existing ArrayList

I have a method that writes my objects in to a JSON file, is there a way I can read the objects and store them back in to an ArrayList? Ideally I would like to store the objects in to the 'music' ArrayList.
Write to JSON method:
public class TimelineLayout extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel timelineLabel;
static ArrayList<Music> music = new ArrayList<>();
public static void saveMusic(ArrayList<Music> music, String filename) {
String fn;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(music, new TypeToken<ArrayList<Music>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String json = gson.toJson(jsonArray);
try {
//write converted json data to a file named "objects.json"
if (filename != null) {
fn = "objects.json";
} else {
fn = filename + ".json";
}
FileWriter writer = new FileWriter(fn);
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON Objects:
[{
"artist": "Usher",
"title": "U got it bad",
"genre": "Pop",
"duration": 3.01,
"year": 2003
},
{
"artist": "Coldplay",
"title": "Viva la vida",
"genre": "Rock n ",
"duration": 2.56,
"year": 2001
}
]
Trying to parse using GSON library:
public static List<Music> loadMusic() {
ArrayList<Music> musicList = new ArrayList<>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
try {
BufferedReader br = new BufferedReader(new FileReader("objects.json"));
JsonElement jsonElement = jsonParser.parse(br);
//Create generic type
java.lang.reflect.Type type = new TypeToken<List<Music>>() {
}.getType();
return gson.fromJson(jsonElement, type);
} catch (IOException e) {
e.printStackTrace();
}
return musicList;
}

Gson only parsing one object correctly from JSON?

I have the following JSON:
{
"Person": {
"id": "1",
"name": "sampleName"
},
"PersonCalender ": {
"start": "2017-01-25T19:00:00+0100",
"End": "2019-05-10T19:00:00+0100"
}
}
This is its corresponding Java Object (containing 2 objects):
public class PersonRequest {
private Person person;
private PersonCalender personCalender;
//getters and setters
}
Below shows how I am trying to parse the object, however only the Person object is getting correctly parsed.
Am I making a mistake or is the my JSON not valid to be parsed by into this object using Gson?
Gson Parsing:
PersonRequest personRequest = new PersonRequest();
try {
InputStream is = PersonTest.class.getResourceAsStream("/my/path/personRequest.json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
Gson gson = new Gson();
personRequest = gson.fromJson(bufferedReader, PersonRequest.class);
} catch (Exception e) {
logger.logMessage("Exception: " + e);
}
You have two errors here. 1 - space after PersonCalender, 2- The first letter in PersonCalender should be lowercase (according to your java code)

Android - Save JSON from InputStream into String

I'm trying to parse this JSON I get from a HttpURLConnection in Android.
{
"responsejson":
{
"value1": [
{
"data": "Call",
"label": "Call",
"default": false
},
{
"data": "Email",
"label": "Email",
"default": false
}
],
"value2": [
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": true,
"TechLabel": "NotStarted",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": false,
"TechLabel": "InProgress",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": true,
"IsDefault": false,
"TechLabel": "Completed",
"Id": "01Jb"
}
],
...
}
}
What I want to do is save the content of value1 in a string, the content of value2 in another string,... because I need to store it in the database, so in the future I can load and parse it. I am using JsonReader but it's not possible to do this with JsonReader.
// ...
inputStream = conn.getInputStream();
JsonReader json = new JsonReader(new InputStreamReader(in));
json.beginObject();
while (json.hasNext()) {
String valueName = json.nextName();
// String content = ?????
}
json.endObject();
// ...
Any ideas? Custom objects are not possible due to we never know which values the JSON is going to show.
Use this to convert JSON array to string
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Use Gson to parse the JSON that you receive in InputStream. Then you can get the ArrayList from that parsed object. Again, use Gson to serialize the arraylist back to JSON.
This code works for your example json.
public class Value1 {
public String data,label;
#SerializedName("default")
public boolean isdefault;
}
public class Value2 {
public Attributes attributes;
public boolean IsOpened,IsDefault;
public String TechLabel,Id;
}
public class Attributes {
public String type,url;
}
String jsonString = "{\"responsejson\":{\"value1\":[{\"data\":\"Call\",\"label\":\"Call\",\"default\":false},{\"data\":\"Email\",\"label\":\"Email\",\"default\":false}],\"value2\":[{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":true,\"TechLabel\":\"NotStarted\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":false,\"TechLabel\":\"InProgress\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":true,\"IsDefault\":false,\"TechLabel\":\"Completed\",\"Id\":\"01Jb\"}]}}";
try {
org.json.JSONObject object = new JSONObject(jsonString);
jsonString = object.getString("responsejson");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(jsonString).getAsJsonObject();
List<Value1> list1 = new Gson().fromJson(obj.get("value1"), new TypeToken<List<Value1>>() {}.getType());
List<Value2> list2 = new Gson().fromJson(obj.get("value2"), new TypeToken<List<Value2>>() {}.getType());
Since you do not know json structure beforehand, your best bet is to use GSON 2.0 feature that supports default maps and lists.
Use the following code to deserialize :
Object object = new Gson().fromJson(jsonString, Object.class);
The created object is a Map (com.google.gson.internal.LinkedTreeMap) which looks like this (for the above example)
{responsejson={value1=[{data=Call, label=Call, default=false}, {data=Email, label=Email, default=false}], value2=[{attributes={type=Status, url=/...}, IsOpened=false, IsDefault=true, TechLabel=NotStarted, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=false, IsDefault=false, TechLabel=InProgress, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=true, IsDefault=false, TechLabel=Completed, Id=01Jb}]}}
Use the generated object, parse it and save it in your db.
You can serialize that map back to JSON using :
String json = new Gson().toJson(object);
Hope this helps you.
just read the stream regularly and save it into a regular String, then parse that String :
// to get the general object that contains all the values
JSONObject json = new JSONObject(json_readed);
JSONObject response = json.getJSONObject("responsejson");
// to get the values
List<JSONArray> all_values = new ArrayList<JSONArray>();
Iterator<?> keys = response.keys();
while( keys.hasNext() ){
String value = (String)keys.next();
if( response.get(value) instanceof JSONArray ){
all_values.add(response.getJSONArray(value));
}
}
now you have all the values(whatever what's it's name id) combined into that ArrayList called(all_values).
Note that the JSON you provided in your question is missing opening"{" and closing"}" brackets in the beginning and the ending of it.
What you need to do is, first create a JsonObject from the json string representation, at this stage no specifics are given.
JSONObject object = new JSONObject("json_here"); //catch all exceptions thrown.
Interestingly you mentioned that the structure varies, it consider that weird, i am guessing you are pulling from different api instances. What you need to do , create a pojo class mapping the api instance name to the returned json string body.
After you attained the Object of interest, consider using GSON. A Java serialization/deserialization library to convert Java Objects into JSON and back. What you then need to do is to,serialize the pojo class,into an object.Then store into the database. I recommend using realm and not SQLite.
Example serializing the class.
class JClass {
private String jType;
private String json_body;
JClass() {
// no-args constructor
}
}
JClass j = new JClass();
j.jType ="some_type";
j.json_body = "json_body_here";
Gson gson = new Gson();
String json = gson.toJson(j);
then get the json String object, and store in database of choice.
/*
* Method to parse InputStream to String JSON
* */
private String parse(InputStream in){
StringBuilder result;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
return result.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
JSONParser parser = new JSONParser();
List<String> output = new ArrayList<String>();
try {
Object obj = parser.parse(data); // data is JSON
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("value1");
JSONArray msg2 = (JSONArray) jsonObject.get("value2");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
output.add(iterator.next());
}
String[] stringArray = output.toArray(new String[0]);
return stringArray;
} catch (Exception e) {
return null;
}

Categories