I am trying to parse a JSON response. I am getting JSON response like below:
"libraryLastModified" : "2012-10-10 03:57:26",
"playlists" : { "10063" : { "id" : "10063",
"name" : "Favorites",
"songs" : [ "10006134",
"10006053",
"10006274",
"10006167",
]
},
"10157" : { "id" : "10157",
"name" : "80s",
"songs" : [ "10006694",
"10006695",
"10006697",
"10006699",
"10006698",
]
}
How can I access the id & name values?
I love GSON. In this scenario you'd create two classes.
public class PLayList {
private int id;
private String name;
private List<Integer> songs;
//getters and setters
}
public class Library {
private Date libraryLastModified;
private List<Playlist> playlists;
//getters and setters
}
Then you can write
Gson gson = new Gson();
Library result = gson.fromJson(theInput, Library.class);
Since the playlists is coming to you as key:value you'd need to write a custom deserializer for them. Taje a look at GSON deserializing key-value to custom object for how to do that
In pseudocode. I don't remember exactly the JSON methods
JSONObject mainObj = parseJson
JSONObject playLists = mainObj.getJSONObject("playlists")
JSONObject myList = playList.getJSONObject("10063")
id = myList.getString("id")
To iterate over several lists, you'd better transform playlists to a JSONArray, then you can iterate over it. If you can't do that, check the Android JSON API and check how to get all keys for a JSONObject and then iterate over the keys
for(int i=0;i<playlistKeys.length;i++){
playlistObj = playLists.getJSONObject(playlistsKey[i])
}
use google Gson.
http://code.google.com/p/google-gson/
class Response{
Date libraryLastModified;
Playlist []playlists;
class Playlist{
Long id;
String name;
Long[] songs;
}
}
String _response=... //Your response from web
Response response = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create().fromJson(_response, Response.class);
String songName = response.playlists[0].name;
Related
i need to access the values of a Json, that its inside an Array, that its inside of a Json, the structure of the Json file its like this:
{
"Places": [
{
"id": 17,
"city": "Chicago",
"vehicle": "car"
},
{
"id": 13,
"city": "New York",
"vehicle": "plane",
}
]
}
i only need the values of "id", "city" and "vehicle"
im using the map function like this:
Gson gson = new Gson();
Map<String,String> userMap = gson.fromJson(contentoffile, Map.class);
for (Object value : userMap.values()) {
Map places= (Map) value;
int id = (int) (places.get("id"));
String city= (String) places.get("city");
String vehicle= (String) places.get("vehicle");
but i got the next error
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
how i can acces the data?
btw, i can use other libraries for this, not only Map function
The structure you have is a JSON object that contains a JSON array places, I am not really sure what you are trying to achieve by using a Map<String, String>, you need to either create a Place POJO and parse accordingly OR just access it directly as a JsonObject:
Place.java
public class Place
{
private int id;
private String city;
private String vehicle;
public Place(int id, String city, String vehicle)
{
this.id = id;
this.city = city;
this.vehicle = vehicle;
}
// Setters & getters
}
public static void main(String[] args)
{
Gson gson = new Gson();
// Parse your file to a JsonObject
JsonObject jsonObject = gson.fromJson(contentoffile, JsonObject.class);
// Extract JsonArray (places) from JsonObject
JsonArray jsonArray = jsonObject.get("Places").getAsJsonArray();
Option 1: Converting into List<Place>:
// Convert JsonArray to a list of places
Type type = new TypeToken<List<Place>>() {}.getType();
List<Place> places = gson.fromJson(jsonArray, type);
//iterate over places
for (Place place : places)
{
int id = place.getId();
//etc..
}
}
Option 2: Iterating directly over JsonArray:
for (JsonElement jsonElement : jsonArray)
{
//This will represent a Place object
JsonObject curr = jsonElement.getAsJsonObject();
int id = curr.get("id").getAsInt();
String city = curr.get("city").getAsString();
String vehicle = curr.get("vehicle").getAsString();
}
Option 3: Create a wrapper class
public class PlaceWrapper
{
private List<Place> places;
//Const, setters, getters
}
public static void main(String[] args)
{
Gson gson = new Gson();
// Deserialize json
PlaceWrapper placeWrapper = gson.fromJson(contentoffile, PlaceWrapper.class);
// iterate over places
for (Place place : placeWrapper.getPlaces())
{
// do your thing
}
}
stucked at accessing nested json. similar stuff:
[
{
key-value,
key-value
},
{
key-value,
key-value
},
{
key-value,
key-value
}
]
works nicely but when i try:
{
"alfa":{
"id":"foo",
"product":{
"id":"foo1",
"price":"foo2"
}
},
"beta":{
"id":"foo",
"product":{
"id":"foo1",
"price":"foo2"
}
}
}
i get error:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<...
i of course did change structure of classes:
public class Alphabet{
private Purchase purchase;
...
public class Purchase{
private String id;
private Product product;
...
public class Product {
private String id;
private String price;
...
to read it:
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream(new File("src/main/json/file.json"));
TypeReference<List<Alphabet>> typeReference = new TypeReference<List<Alphabet>>() {};
List<Alphabet> alphabet= mapper.readValue(inputStream, typeReference);
System.out.println(alphabet);
whats wrong, please?
It seems like the JSON structure you try to read is not a List<Alphabet>, but a Map<String, Purchase>.
Your second json not like list of object. The second json look lik have 2 main objects if so you need class like below.
public class Alphabet{
private Purchase purchase;
private Purchase purchase1;
}
But it not good practice. Use as first josn like list of objects.
So i made this mini app in purpose of learning JSON
so basically this is the JSON file
{
"Student1" : {
"name" : "Amine" ,
"mark": 19,
"Groupe": "G25"
},
"Student2" : {
"name" : "Zaki" ,
"mark": 19,
"groupe": "G25",
}
}
i tried instead of Putting "Student1" i thought i could do something like "Student"+"1"
private void parseJson(String toString) {
TextView showView = new TextView(this);
theLayout.addView(showView);
StringBuilder builder = new StringBuilder();
try {
JSONObject root = new JSONObject(toString);
/////// Here i got the INPUT string from an EditText
///// i think i should use some thing like .equals()
String theWantedStudent = "Student"+INPUT ;
JSONObject student = root.getJSONObject(theWantedStudent);
builder.append("Name : ")
.append(student.getString("name")).append("\n");
builder.append("Groupe : ")
.append(student.getString("groupe")).append("\n");
builder.append("Mark : ")
.append(student.getInt("mark")).append("\n");
} catch (JSONException e) {
e.printStackTrace();
}
showView.setText(builder.toString());
}
if there is a simpler methode let me know
thanks
I think what you want is a list of student ojects:
[
{
"name" : "Amine" ,
"mark": 19,
"groupe": "G25"
},
{
"name" : "Zaki" ,
"mark": 19,
"groupe": "G25"
}
]
Then use a class such as:
public class Student {
#JsonProperty("name")
private String name;
#JsonProperty("mark")
private Integer mark;
#JsonProperty("groupe")
private String groupe;
//getters and setters
}
Then use jackson to iterate thru the list
I recommend to use Gson to parse the JSON into an object.
After that, it will be easier to manipulate the data.
First, create a Java class with yout JSON structure:
public class Student {
private String name;
private int mark;
private String group;
// add the getters and setters
}
Then, use Gson to parse to the object:
Student student = new Gson().fromJson(json, Student.class);
If you want to build a JSON from an object use the Gson's method toJson:
Student student = new Student();
student.setName("Peter");
student.setMark(10);
student.setGroup("ABC");
String json = new Gson().toJson(student);
If you wanna more information about Gson check this tutorial, it's really good: https://mkyong.com/java/how-to-parse-json-with-gson/
I have a JSON object stored in db in the form of string. I am using it to create dynamic form in the UI. Now the problem is I want to change some values in it based on other changes happening on the application. So suppose I updated label for the field, then I have to get this JSON and change that here.
This would be easy If I have stored same type of objects in this json, but my JSON is like follows:
[{
"name": "someName",
"xtype": "keyvaluecombo",
"fieldLabel": "Some Title",
"refType": "YES_NO",
"multiSelect": false,
"helpText": ""
},
{
"name": "someName2",
"xtype": "keyvaluecombo",
"fieldLabel": "Some Title2",
"refType": "YES_NO",
"multiSelect": false,
"helpText": ""
},
{
"xtype": "datefield",
"fieldLabel": "Joining Date",
"name": "joiningDate",
"submitFormat": "Y-m-d"
},
{
"xtype": "userselectioncombo",
"fieldLabel": "Selection",
"name": "selections",
"filterBy": {
"functions": [
"select"
]
}
}]
Now this is stored as String in db, what is efficient way of changing fieldLabel based on name. I could have tried working on it as string only and use regular expression, but that didn't feel right.
You should write a bean class, which should be mapping to you Json object like,
public class abc {
private String name;
private String xtype;
private String fieldLabel;
........
}
Then you should use
import java.lang.reflect.Type;
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Type type = new TypeToken<List<abc>>() {
}.getType();
List<abc> abcList = gson.fromJson(confTemplate,
type); // confTemplate is your Json object you get from DB
this will get the list of beans.
for (abc abcData : abcList ) {
// you can do your stuff
}
First of all the best way, changing your database design with a new one that suits your model. Not keeping json in your database as a column. But if you can't do that, because sometimes it's impossible to change old db designs you can trace the following way.
And of course you should read your json from db before start and save it again after the below process.
Create a custom object that suits your model.
public class MyObject{
private String name;
private String fieldLabel;
public String getFieldLabel(){
return fieldLabel;
}
public void setFieldLabel( String fieldLabel ){
this.fieldLabel = fieldLabel;
}
public String getName(){
return name;
}
public void setName( String name ){
this.name = name;
}
// bla bla other fields
Convert your json into your object, and vice versa see the code example below:
public static void main( String[] args ){
Gson gson = new Gson();
String yourJson = "[{'name':'someName','xtype':'keyvaluecombo','fieldLabel':'Some Title','refType':'YES_NO','multiSelect':false,'helpText':''},{'name':'someName2','xtype':'keyvaluecombo','fieldLabel':'Some Title2','refType':'YES_NO','multiSelect':false,'helpText':''},{'xtype':'datefield','fieldLabel':'Joining Date','name':'joiningDate','submitFormat':'Y-m-d'},{'xtype':'userselectioncombo','fieldLabel':'Selection','name':'selections','filterBy':{'functions':['select']}}]";
// changing single quotes with double ones.
yourJson = yourJson.replaceAll( "'", "\"" );
JsonArray jsonArray = new JsonParser().parse( yourJson ).getAsJsonArray();
List<MyObject> result = new ArrayList<MyObject>();
for( JsonElement jsonElement : jsonArray ){
MyObject myObject = gson.fromJson( jsonElement, MyObject.class );
// change fields as you wish
if( myObject.getName().equals( "someName" ) ){
myObject.setFieldLabel( "TEST" );
}
// add it to another list
result.add( myObject );
}
// convert into another json again..
System.out.println( gson.toJson( result ) );
}
Easy to realize that Object in your list have attributes below:
"name"
"xtype"
"fieldLabel"
"refType"
"multiSelect"
"helpText"
"submitFormat"
"filterBy"
So you can create an Object which has over attributes. Using ObjectMapper for deserialize the list:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, new TypeReference<ArrayList<T>>() {})
After have a list object you can loop for change any attribute or change attribute of an specific item you want.
I'm trying to parse some JSON data using gson in Java that has the following structure but by looking at examples online, I cannot find anything that does the job.
Would anyone be able to assist?
{
"data":{
"id":[
{
"stuff":{
},
"values":[
[
123,
456
],
[
123,
456
],
[
123,
456
],
],
"otherStuff":"blah"
}
]
}
}
You just need to create a Java class structure that represents the data in your JSON. In order to do that, I suggest you to copy your JSON into this online JSON Viewer and you'll see the structure of your JSON much clearer...
Basically you need these classes (pseudo-code):
class Response
Data data
class Data
List<ID> id
class ID
Stuff stuff
List<List<Integer>> values
String otherStuff
Note that attribute names in your classes must match the names of your JSON fields! You may add more attributes and classes according to your actual JSON structure... Also note that you need getters and setters for all your attributes!
Finally, you just need to parse the JSON into your Java class structure with:
Gson gson = new Gson();
Response response = gson.fromJson(yourJsonString, Response.class);
And that's it! Now you can access all your data within the response object using the getters and setters...
For example, in order to access the first value 456, you'll need to do:
int value = response.getData().getId().get(0).getValues().get(0).get(1);
Depending on what you are trying to do. You could just setup a POJO heirarchy that matches your json as seen here (Preferred method). Or, you could provide a custom deserializer. I only dealt with the id data as I assumed it was the tricky implementation in question. Just step through the json using the gson types, and build up the data you are trying to represent. The Data and Id classes are just pojos composed of and reflecting the properties in the original json string.
public class MyDeserializer implements JsonDeserializer<Data>
{
#Override
public Data deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
{
final Gson gson = new Gson();
final JsonObject obj = je.getAsJsonObject(); //our original full json string
final JsonElement dataElement = obj.get("data");
final JsonElement idElement = dataElement.getAsJsonObject().get("id");
final JsonArray idArray = idElement.getAsJsonArray();
final List<Id> parsedData = new ArrayList<>();
for (Object object : idArray)
{
final JsonObject jsonObject = (JsonObject) object;
//can pass this into constructor of Id or through a setter
final JsonObject stuff = jsonObject.get("stuff").getAsJsonObject();
final JsonArray valuesArray = jsonObject.getAsJsonArray("values");
final Id id = new Id();
for (Object value : valuesArray)
{
final JsonArray nestedArray = (JsonArray)value;
final Integer[] nest = gson.fromJson(nestedArray, Integer[].class);
id.addNestedValues(nest);
}
parsedData.add(id);
}
return new Data(parsedData);
}
}
Test:
#Test
public void testMethod1()
{
final String values = "[[123, 456], [987, 654]]";
final String id = "[ {stuff: { }, values: " + values + ", otherstuff: 'stuff2' }]";
final String jsonString = "{data: {id:" + id + "}}";
System.out.println(jsonString);
final Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new MyDeserializer()).create();
System.out.println(gson.fromJson(jsonString, Data.class));
}
Result:
Data{ids=[Id {nestedList=[[123, 456], [987, 654]]}]}
POJO:
public class Data
{
private List<Id> ids;
public Data(List<Id> ids)
{
this.ids = ids;
}
#Override
public String toString()
{
return "Data{" + "ids=" + ids + '}';
}
}
public class Id
{
private List<Integer[]> nestedList;
public Id()
{
nestedList = new ArrayList<>();
}
public void addNestedValues(final Integer[] values)
{
nestedList.add(values);
}
#Override
public String toString()
{
final List<String> formattedOutput = new ArrayList();
for (Integer[] integers : nestedList)
{
formattedOutput.add(Arrays.asList(integers).toString());
}
return "Id {" + "nestedList=" + formattedOutput + '}';
}
}