I am trying get a list object from json file usiong gson. It returning list with objects but all attributes are null. How to get the objects properly?
json file:
[{"PeriodEndP":"2014-04-06T00:00:00","SiteKeyP":"00035"},{"PeriodEndP":"2014-04-06T00:00:00","SiteKeyP":"00035"}]
ScheduleDTO.java
public class ScheduleDTO {
String periodEndP;
String siteKeyP;
}
GsonEx.java
public class GsonEx {
public static void main(String[] args) {
try
{
JsonReader jsonReader = new JsonReader(new FileReader("F:/schedule.txt"));
Gson gson = new Gson();
Type ScheduleMsgDestType = new TypeToken<List<ScheduleDTO>>(){}.getType();
List<ScheduleDTO> ScheduleList = gson.fromJson(jsonReader, ScheduleMsgDestType);
for(ScheduleDTO t :ScheduleList )
{
System.out.println(t.periodEndP);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Make PeriodEndP to periodEndP
and same for SiteKeyP which will be siteKeyP
The names should be the same in the json and code.
Related
I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}
I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
I am trying to build a json string in java but I am a bit confused as how I should go about it. This is what I tried so far.
String jsonString = new JSONObject()
.put("JSON1", "Hello World!")
.put("JSON2", "Hello my World!")
.put("JSON3", new JSONObject()
.put("key1", "value1")).toString();
System.out.println(jsonString);
The output is :
{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
The Json I want is as follows :-
{
"data":{
"nightclub":["abcbc","ahdjdjd","djjdjdd"],
"restaurants":["fjjfjf","kfkfkfk","fjfjjfjf"],
"response":"sucess"
}
}
How should I go about it?
You will need to use JSONArray and JsonArrayBuilder to map these json arrays.
This is the code you need to use:
String jsonString = new JSONObject()
.put("data", new JSONObject()
.put("nightclub", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("restaurants", Json.createArrayBuilder()
.add("abcbc")
.add("ahdjdjdj")
.add("djdjdj").build())
.put("response", "success"))
.toString();
You can use gson lib.
First create pojo object:
public class JsonReponse {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
private String reponse;
private List<String> nightclub;
private List<String> restaurants;
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
public List<String> getNightclub() {
return nightclub;
}
public void setNightclub(List<String> nightclub) {
this.nightclub = nightclub;
}
public List<String> getRestaurants() {
return restaurants;
}
public void setRestaurants(List<String> restaurants) {
this.restaurants = restaurants;
}
}
}
and next complite data and generate json:
JsonReponse jsonReponse = new JsonReponse();
JsonReponse.Data data = jsonReponse.new Data();
data.setReponse("sucess");
data.setNightclub(Arrays.asList("abcbc","ahdjdjd","djjdjdd"));
data.setRestaurants(Arrays.asList("fjjfjf","kfkfkfk","fjfjjfjf"));
jsonReponse.setData(data);
Gson gson = new Gson();
System.out.println(gson.toJson(jsonReponse));
What I am trying to do, and I don't know whether this is possible, is to get the class type of an object, and then use it in a declaration. I am using the Gson library for Json Conversion and I want to create a method that can take any object Arraylist type and convert it into a JsonArray. What I have below is code. Arraylist of type X will are casted down to type Object and than passed to the method below. The INSERT_CLASS_HERE should be dynamic based on the Object type.
public static JsonArray getJsonArray(List<Object> list , Class theClass){
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<INSERT_CLASS_TYPE_HERE>>() {}.getType());
if (! element.isJsonArray()) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
What I tried was the following but this isn't correct syntax and will throw errors
public static JsonArray getJsonArray(List<Object> list , Class theClass){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<theClass>>() {}.getType());
if (! element.isJsonArray()) {
// fail appropriately
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
1) Is this possible to do, and if not why not?
2) If it is not, how can this be achieved?
Thank you!
Why are you passing in a type value? That should not be required.
public static JsonArray getJsonArray(List<Object> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list);
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
Better yet to avoid casting you can do the following
public static <T> JsonArray getJsonArray(List<T> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list);
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
It seems what you are trying to do is along the lines of Java generics.
This should be fairly simply to do using generics:
public static <T> JsonArray getJsonArray(List<T> list){
if(list.size() == 0) return null;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(list, new TypeToken<List<T>>() {}.getType());
//Not familiar with gson, but you might be able to just use T here instead
Try modifying your method signature like this:
public static <T> JsonArray getJsonArray(List<Object> list, Class<T> theClass )
You should then be able to do this:
new TypeToken<List<T>>
I'm using this method to parse a JSON string, but it is too slow... is there a better way to do it?
Thanks
synchronized private void parseCategories(String response){
try{
JSONArray categoriesJSONArray = new JSONArray (response);
// looping through All Contacts
for(int i = 0; i < categoriesJSONArray.length(); i++){
JSONObject currentCategory = categoriesJSONArray.getJSONObject(i);
String label="";
String categoryId="";
// Storing each json item in variable
if(currentCategory.has("label"))
label = currentCategory.getString("label");
if(currentCategory.has("id"))
categoryId = currentCategory.getString("id");
if(
label!=null &&
categoryId!=null
)
{
Category toAdd = new Category(categoryId, label);
categories.add(toAdd);
}
}
//Alphabetic order
Collections.sort(
categories,
new Comparator<Feed>() {
public int compare(Feed lhs, Feed rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
}
);
Intent intent = new Intent("CategoriesLoaded");
LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
}catch (JSONException e) {
e.printStackTrace();
}
}
Here's try following code to start with. You would need Gson library for it.
Gson gson=new Gson();
MyBean myBean=gson.fromJson(response);
Note: Here MyBean class contains the fields present in you json string for e.g. id, along with getter and setters. Rest of all is handled by Gson.
Here's a quick demo.
import com.google.gson.annotations.SerializedName;
public class Box {
#SerializedName("id")
private String categoryId;
// getter and setter
}
Say you JSON looks as following:
{"id":"A12"}
You can parse it as follows:
class Parse{
public void parseJson(String response){
Gson gson=new Gson();
Box box=gson.fromJson(response,Box.class);
System.out.println(box.getCategoryId());
}
}
Output :
A12
For more on Gson visit here
Use GSON library. You can convert your object to json string like the following example:
MyClass MyObject;
Gson gson = new Gson();
String strJson = gson.toJson(MyObject);