Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A have a hard string from Json. Example:
[
{
"Group1": [
{
"id": "2b3b0db",
"name": "Ivan"
},
{
"id": "4f3b0db",
"name": "Lera"
}
]
},
{
"Group2": [
{
"id": "42ae2a7",
"name": "Victor"
}
]
}
]
How i can parse it from Gson? Thanks!
This link describes json to java and java to json using Gson
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Json to Java using GSON
Gson gson = new Gson();
try {
BufferedReader br = new StringReader(<CONTENT>);
//convert the json string back to object
// In your case this is Group object
Object obj = gson.fromJson(br, Object .class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
Java Object to json String using GSON
Object obj = new Object();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
In your case use this :
public static void main(final String[] args) {
String Group1 = " [ { \"id\": \"2b3b0db\", \"name\": \"Ivan\" }, { \"id\": \"4f3b0db\", \"name\": \"Lera\" } ] ";
Gson gson = new Gson();
Group[] object = gson.fromJson(new StringReader(Group1), Group[].class);
System.out.println(object);
}
public class Group {
private String id;
private String name;
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setId(final String id) {
this.id = id;
}
}
try following code
public String parse(String jsonLine)
{
JSONArray jArraymain=new JSONArray(jsonLine);
JSONObject jobject=array.getJSONObject(0);
JSONArray jArraySub=jobject.getJSONArray("Group1");
for(int i=0;i<=jobject.length;i++)
{
String temp=jArraySub.get(i).toString();
}
}
also you can use this
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
Below will help you. I havnt executed the below code snippet yet.
JsonElement jelement = new JsonParser().parse("json data");
JsonArray jgrouparray = jelement.getAsJsonArray();
for(int i=0; i<jgrouparray.size(); i++){
JsonArray jgroup = jgrouparray.get(i).getAsJsonArray("Group"+i);
for(int j=0; j<jgroup.size(); j++){
JsonObject jobject = jgroup.get(j).getAsJsonObject();
String id = jobject.get("id").toString();
String name = jobject.get("name").toString();
}
}
For more info look into: JSON parsing using Gson for Java
Do you have to use GSON? If you can use JSONObject from json.org you can almost get it:
URL url = this.getClass().getClassLoader().getResource("json" + File.separator + "GroupJson.json");
JSONArray jsonArray = new JSONArray(FileUtil.readFile(url.getPath()));
JSONObject jsonObject = jsonArray.getJSONObject(0);
log.info("{}", jsonObject.toString());
this outputs: {"Group1":[{"id":"2b3b0db","name":"Ivan"},{"id":"4f3b0db","name":"Lera"}]}
Related
I have some problem fetching info from JSON. I'm confused about whether to use ArrayList or any other data type to retrieve data from JSON server.
I've tried to fetch data using
ArrayList<String>
in model.
Below is data format of JSON
[
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
},
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
}
]
I want to fetch all sun_timing data and mon_timing data.
That is sun_from,sun_to and mon_from,mon_to data.
Your Plain Old Java Object(POJO) for your json looks like this:
public class Example {
#SerializedName("sun_timing")
#Expose
private String sunTiming;
#SerializedName("mon_timing")
#Expose
private String monTiming;
public String getSunTiming() {
return sunTiming;
}
public void setSunTiming(String sunTiming) {
this.sunTiming = sunTiming;
}
public String getMonTiming() {
return monTiming;
}
public void setMonTiming(String monTiming) {
this.monTiming = monTiming;
}
}
See also: https://stackoverflow.com/a/40973753/10452701 for more details about How to get json via Rerofit2.
try this out working for me
private List<String> getSunList() {
ArrayList sunList = new ArrayList<String>()
String sun_json = your_json_string
try {
JSONObject jsonObject = new JSONObject(sun_json)
Log.d(TAG, "jsonObject: "+jsonObject)
Log.d(TAG, "jsonObject: "+sun_json)
JSONArray jsonArray = jsonObject.getJSONArray("sun_timing")
for (i in 0 until jsonArray.length())
{
JSONObject obj = jsonArray.get(i) as JSONObject
String sun_from = obj.getString("sun_from")
String sun_to = obj.getString("sun_to")
sunList.add(sun_from)
Log.d(TAG, "obj= "+obj)
}
}
catch (e: java.lang.Exception)
{
}
return sunList
}
I have the following json
"notes": {"note": [
{
"content": "Having wisdom teeth removed.",
"from": "employee"
},
{
"content": "Get well soon",
"from": "manager"
}
]},
the issue is that the value coud also be
"notes": "",
or
"notes": {"note": {
"content": "This is a test note.",
"from": "employee"
}},
and storing it in these
public class Notes
{
#SerializedName ("note")
public List<Note> note;
}
public class Note
{
#SerializedName ("content")
public String content;
#SerializedName ("from")
public String from;
}
I believe I solved the issue of not being an array but being an single object by doing this
public class Json {
private static Gson gson;
private static class MyNoteClassTypeAdapter implements JsonDeserializer<List<RequestsDTO.Note>> {
public List<RequestsDTO.Note> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<RequestsDTO.Note> vals = new ArrayList<RequestsDTO.Note>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((RequestsDTO.Note) ctx.deserialize(e, RequestsDTO.Note.class));
}
} else if (json.isJsonObject()) {
vals.add((RequestsDTO.Note) ctx.deserialize(json,RequestsDTO.Note.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
}
public static Gson getGson()
{
if (gson == null)
{
Type ListType = new TypeToken<List<RequestsDTO.Note>>() {}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer());
builder.registerTypeAdapter(ListType, new MyNoteClassTypeAdapter());
gson = builder.create();
}
return gson;
}
}
And now I am stuck on when the whole thing just comes back as a string....
Refer the code snippet below to deserialize your json using Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("note");
if(elem.isJsonArray()) { //**Array**
List<Note> notelist = gson.fromJson(elem.toString(), new TypeToken<List<Note>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), Note.class);
} else { //**String**
String note = elem.toString();
}
The idea is try to get "note" field (from "notes" JSONObject) as JSONArray first and if it throws exception that will mean that there is no "note" JSONArray into "notes" JSONObject and that will mean that "note" is JSONObject. The same way we can figure out situation when note field is String.
try {
//String jsonString="{\"notes\": {\"note\": [{\"content\": \"Having wisdom teeth removed.\",\"from\": \"employee\" }, {\"content\": \"Get well soon\", \"from\": \"manager\"} ] }}";
//String jsonString="{\"notes\": { \"note\": {\"content\": \"This is a test note.\",\"from\": \"employee\"}}}";
String jsonString="{\"notes\": { \"note\": \"\"}}";
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject jsonObjectNotes=jsonObject.getJSONObject("notes");
try{
JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray("note");
for (int i = 0; i < jsonArrayNote.length(); i++) {
JSONObject jsonObject2= jsonArrayNote.getJSONObject(i);
String stringContent=jsonObject2.getString( "content");
String stringFrom= jsonObject2.getString( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
}
catch(JSONException e){
//that means that jsonObjectNotes has no jsonArray with name "notes" and "notes" is jsonObject
try{
JSONObject jsonObject3=jsonObjectNotes.getJSONObject("note");
String stringContent=(String) jsonObject3.get( "content");
String stringFrom=(String) jsonObject3.get( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
catch(JSONException ex){
//that means that jsonObjectNotes has no jsonObject with name "notes" and "notes" is empty String
String stringNote=jsonObjectNotes.getString("note") ;
Log.e(getClass().getName(), "note is string ="+ stringNote);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In my example code another get operations can also throw jsonExceptions but I think you get the idea.
Have a look at Genson library http://code.google.com/p/genson/.
If your classes are inner classes make them static.
The following code should solve your problem.
Genson genson = new Genson.Builder().withDeserializerFactory(new NotesDeserializerFactory()).create();
Notes notes = genson.deserialize(in, Notes.class);
// Define a factory so you can delegate the deserialization to existing mechanisms for lists and beans
class NotesDeserializerFactory implements Factory<Deserializer<Notes>> {
#Override
public Deserializer<Notes> create(Type type, Genson genson) {
Converter<List<Note>> noteListConverter = genson.provideConverter(new GenericType<List<Note>>() {}.getType());
Converter<Note> noteConverter = genson.provideConverter(Note.class);
return new NotesDeserializer(noteListConverter, noteConverter);
}
}
// define an implementation for you Notes class so you can handle the different cases
class NotesDeserializer implements Deserializer<Notes> {
private final Converter<List<Note>> noteListConverter;
private final Converter<Note> noteConverter;
public NotesDeserializer(Converter<List<Note>> noteListConverter,
Converter<Note> noteConverter) {
this.noteListConverter = noteListConverter;
this.noteConverter = noteConverter;
}
#Override
public Notes deserialize(ObjectReader reader, Context ctx) throws TransformationException,
IOException {
Notes notes = new Notes();
if (reader.getValueType() == ValueType.ARRAY) notes.note = noteListConverter.deserialize(reader, ctx);
else if (reader.getValueType() == ValueType.OBJECT) notes.note = Arrays.asList(noteConverter.deserialize(reader, ctx));
else { // it is a litteral (string, numeric, boolean, null)
notes.note = new ArrayList<Note>();
}
return notes;
}
}
I have a JSON data in the following format,
[
{
"name": "France",
"date_time": "2015-05-17 19:59:00",
"dewpoint": "17",
"air_temp": "10.8"
},
{
"name": "England",
"date_time": "2015-05-17 19:58:48",
"dewpoint": "13",
"air_temp": "10.6"
},
{
"name": "Ireland",
"date_time": "2015-05-17 19:58:50",
"dewpoint": "15",
"air_temp": "11.1"
}
]
I have a Google map set up already for the Android app, so i have a pass the name value between two activity(GoogleMaps.java & WeatherInfo.java), now when i click a point in Google Map, it will pass the name to WeatherInfo.java, i want get the weather data for that name.
for example: i click France point in the map, The WeatherInfo.class will get the name is "France" and print out the "date_time, dewpoint, air_temp" for that point.
My question is how can i get the Json data parsed only for the point i clicked in the map? Can anyone look at the for loop in my WeatherInfo.java class?
WeatherInfo.java
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String date_time = c.getString(TAG_DATE);
String temp = c.getString(TAG_TEMP);
String dewpoint = c.getString(TAG_DEWPOINT);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_DATE, date_time);
contact.put(TAG_TEMP, temp);
contact.put(TAG_DEWPOINT, dewpoint);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
String name = jsonObject.getString("name");
String date = jsonObject.getString("date_time");
...
}
Or
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
City city = new City();
city.name = jsonObject.getString("name");
...
}
You could use Jackson json parser as follows:-
you will need a value object for the point data.
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Point {
private final String name;
private final String dateTime;
private final int dewpoint;
private final double airTemp;
#JsonCreator
public Point(#JsonProperty("name") final String name, #JsonProperty("date_time") final String dateTime, #JsonProperty("dewpoint") final int dewpoint, #JsonProperty("air_temp") final double airTemp) {
this.name = name;
this.dateTime = dateTime;
this.dewpoint = dewpoint;
this.airTemp = airTemp;
}
public String getName() {
return name;
}
public String getDateTime() {
return dateTime;
}
public int getDewpoint() {
return dewpoint;
}
public double getAirTemp() {
return airTemp;
}
}
Then this Jackson Object Mapper
// 2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
Point[] points = mapper.readValue(new File("points.json"), Point[].class);
for (Point point : points) {
System.out.println("" + point.getName());
System.out.println("" + point.getDateTime());
System.out.println("" + point.getDewpoint());
System.out.println("" + point.getAirTemp());
}
I have the following json
"notes": {"note": [
{
"content": "Having wisdom teeth removed.",
"from": "employee"
},
{
"content": "Get well soon",
"from": "manager"
}
]},
the issue is that the value coud also be
"notes": "",
or
"notes": {"note": {
"content": "This is a test note.",
"from": "employee"
}},
and storing it in these
public class Notes
{
#SerializedName ("note")
public List<Note> note;
}
public class Note
{
#SerializedName ("content")
public String content;
#SerializedName ("from")
public String from;
}
I believe I solved the issue of not being an array but being an single object by doing this
public class Json {
private static Gson gson;
private static class MyNoteClassTypeAdapter implements JsonDeserializer<List<RequestsDTO.Note>> {
public List<RequestsDTO.Note> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<RequestsDTO.Note> vals = new ArrayList<RequestsDTO.Note>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
vals.add((RequestsDTO.Note) ctx.deserialize(e, RequestsDTO.Note.class));
}
} else if (json.isJsonObject()) {
vals.add((RequestsDTO.Note) ctx.deserialize(json,RequestsDTO.Note.class));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return vals;
}
}
public static Gson getGson()
{
if (gson == null)
{
Type ListType = new TypeToken<List<RequestsDTO.Note>>() {}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer());
builder.registerTypeAdapter(ListType, new MyNoteClassTypeAdapter());
gson = builder.create();
}
return gson;
}
}
And now I am stuck on when the whole thing just comes back as a string....
Refer the code snippet below to deserialize your json using Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("note");
if(elem.isJsonArray()) { //**Array**
List<Note> notelist = gson.fromJson(elem.toString(), new TypeToken<List<Note>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), Note.class);
} else { //**String**
String note = elem.toString();
}
The idea is try to get "note" field (from "notes" JSONObject) as JSONArray first and if it throws exception that will mean that there is no "note" JSONArray into "notes" JSONObject and that will mean that "note" is JSONObject. The same way we can figure out situation when note field is String.
try {
//String jsonString="{\"notes\": {\"note\": [{\"content\": \"Having wisdom teeth removed.\",\"from\": \"employee\" }, {\"content\": \"Get well soon\", \"from\": \"manager\"} ] }}";
//String jsonString="{\"notes\": { \"note\": {\"content\": \"This is a test note.\",\"from\": \"employee\"}}}";
String jsonString="{\"notes\": { \"note\": \"\"}}";
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject jsonObjectNotes=jsonObject.getJSONObject("notes");
try{
JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray("note");
for (int i = 0; i < jsonArrayNote.length(); i++) {
JSONObject jsonObject2= jsonArrayNote.getJSONObject(i);
String stringContent=jsonObject2.getString( "content");
String stringFrom= jsonObject2.getString( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
}
catch(JSONException e){
//that means that jsonObjectNotes has no jsonArray with name "notes" and "notes" is jsonObject
try{
JSONObject jsonObject3=jsonObjectNotes.getJSONObject("note");
String stringContent=(String) jsonObject3.get( "content");
String stringFrom=(String) jsonObject3.get( "from");
Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
}
catch(JSONException ex){
//that means that jsonObjectNotes has no jsonObject with name "notes" and "notes" is empty String
String stringNote=jsonObjectNotes.getString("note") ;
Log.e(getClass().getName(), "note is string ="+ stringNote);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
In my example code another get operations can also throw jsonExceptions but I think you get the idea.
Have a look at Genson library http://code.google.com/p/genson/.
If your classes are inner classes make them static.
The following code should solve your problem.
Genson genson = new Genson.Builder().withDeserializerFactory(new NotesDeserializerFactory()).create();
Notes notes = genson.deserialize(in, Notes.class);
// Define a factory so you can delegate the deserialization to existing mechanisms for lists and beans
class NotesDeserializerFactory implements Factory<Deserializer<Notes>> {
#Override
public Deserializer<Notes> create(Type type, Genson genson) {
Converter<List<Note>> noteListConverter = genson.provideConverter(new GenericType<List<Note>>() {}.getType());
Converter<Note> noteConverter = genson.provideConverter(Note.class);
return new NotesDeserializer(noteListConverter, noteConverter);
}
}
// define an implementation for you Notes class so you can handle the different cases
class NotesDeserializer implements Deserializer<Notes> {
private final Converter<List<Note>> noteListConverter;
private final Converter<Note> noteConverter;
public NotesDeserializer(Converter<List<Note>> noteListConverter,
Converter<Note> noteConverter) {
this.noteListConverter = noteListConverter;
this.noteConverter = noteConverter;
}
#Override
public Notes deserialize(ObjectReader reader, Context ctx) throws TransformationException,
IOException {
Notes notes = new Notes();
if (reader.getValueType() == ValueType.ARRAY) notes.note = noteListConverter.deserialize(reader, ctx);
else if (reader.getValueType() == ValueType.OBJECT) notes.note = Arrays.asList(noteConverter.deserialize(reader, ctx));
else { // it is a litteral (string, numeric, boolean, null)
notes.note = new ArrayList<Note>();
}
return notes;
}
}
I'm new to java so this is a bit confusing
I want to get json formatted string
The result I want is
{ "user": [ "name", "lamis" ] }
What I'm currently doing is this :
JSONObject json = new JSONObject();
json.put("name", "Lamis");
System.out.println(json.toString());
And I'm getting this result
{"name":"Lamis"}
I tried this but it didnt work
json.put("user", json.put("name", "Lamis"));
Try this:
JSONObject json = new JSONObject();
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());
However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.
Why do you think the "correct" result is better?
Another way of doing it is to use a JSONArray for presenting a list
JSONArray arr = new JSONArray();
arr.put("name");
arr.put("lamis");
JSONObject json = new JSONObject();
json.put("user", arr);
System.out.println(json); //{ "user": [ "name", "lamis" ] }
Probably what you are after is different than what you think you need;
You should have a separate 'User' object to hold all properties like name, age etc etc.
And then that object should have a method giving you the Json representation of the object...
You can check the code below;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public JSONObject toJson() {
try {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("age", age);
return json;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User lamis = new User("lamis", 23);
System.out.println(lamis.toJson());
}
}