I have the following string:
{
"id":398225253590019,
"zip":"11375",
"street":"70-30 Austin St.",
"state":"NY",
"longitude":-73.845858172784,
"latitude":40.720457257566,
"country":"United States",
"city":"Forest Hills"
}
Please can anyone suggest me a convenient method for parsing it so that I can make a single object of the various components.
import org.json.JSONException;
import org.json.JSONObject;
...
...
String jsonstring = "{
"id":398225253590019,
"zip":"11375",
"street":"70-30 Austin St.",
"state":"NY",
"longitude":-73.845858172784,
"latitude":40.720457257566,
"country":"United States",
"city":"Forest Hills"
}";
JSONObject jObject = null;
try{
jObject = new JSONObject(jsonstring);
catch(JSONException e) {
//Json parse error usually
}
It is a JSON.
You can parset the String into JSONObject. Look the example of JSONTokenizer
That format is called json:
1.You can first create an object (Say "Object") with variables id,zip,country etc and getters and setters.
2.Download Link for jackson.
3.Import the library to your project.
Then just two lines of code:
ObjectMapper mapper = new ObjectMapper();
Object object = mapper.readValue(json, Object.class);
This Object class will contain the values...
Jackson Tutorial.
Related
from server i'm getting json response...but it contais data of two objects..one is of ArrayList Type and 2nd is one POJO(HomeVO) class. i want to split data and store into different objects. i am usnig GSON api.
Servlet:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(questions));
response.getWriter().write(new Gson().toJson(homeVo));
Json Response:
[{"questionId":2,"question":"Quality","typeOfQuestion":2}, {"questionId":3,"question":"Satisfaction","typeOfQuestion":1},{"questionId":4,"question":"overall","typeOfQuestion":2}]{"feedbackName":"IMS","expiryDate":"2014-12-12","createdDate":"2014-10-24","feedbackId":2}
Android Parsing:
HttpClient httpClient = WebServiceUtils.getHttpClient();
try {
HttpResponse response = httpClient.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
data = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
e.printStackTrace();
Log.i("json array",
"While getting server response server generate error. ");
}
You have two choices:
1. Manually parse the strings (What is not recommended)
2. Convert the JSon objects into objects using Gson and then convert it back into one json object also using Gson.
Let me know, if you need more detailed info
More expl.:
Lets say u have two different JSon string, called JsonA and JSonB.
in order to join them, you have to download the Gson library
class AClass{
int idA;
String nameA;
} // Note that the variable's names must be the same as the identifiers in JSON
class BClass{
int idB;
String nameB;
}
class JoinedClass{
BClass bClass;
AClass aClass; //don't forget getters and setters
}
public String joinJson(String JsonA , String JsonB){
Gson gson = new Gson();
AClass aClass = new AClass();
BClass bClass = new BClass();
aClass = gson.fromJson(JsonA, AClass.class);
bClass = gson.fromJson(JsonB, BClass.class);
JoinedClass joinedClass = new JoinedClass();
joinedClass.setAClass(aClass );
joinedClass.setBClass(bClass);
return gson.toJson(joinedClass);
}
// but you know, just after writing this code, i found that there might be an easier way to do this.
// Thanks for attention!
I believe you have two POJO classes for Questions and HomeVO. Then follow these steps:
You can create another DTO with two lists (questions and homeVo).
public class ResultDTO {
private List < HomeVO > homeVoList;
private List < Question > questionList;
//use your getters and setters here:
}
now, use those setters to set your values like you have already done.
then pass that object (ResultDTO) to your gson:
//assuming the ResultDTO object name is resultDto...
response.getWriter().write(new Gson().toJson(resultDto));
now if you check the result in client side, you may have a json response like below:
[questionList: [{
"questionId": 2,
"question": "Quality",
"typeOfQuestion": 2
}, {...}, ],
homeVoList: [{
"feedbackName": "IMS",
"expiryDate": "2014-12-12",
"createdDate": "2014-10-24",
"feedbackId": 2
}, {..}]
so you can get your json objects in response divided like this (this is for web, I dont know how you access it):
//assuming the json reponse is 'data':
var homeVoList = data.homeVoList;
var questionList = data.questionList;
try and see... just a guidance...haven't try actually..
Problem: parse the following response from Foursquare Venues API:
{
meta: {
code: 200
}
notifications: [
{
type: "notificationTray"
item: {
unreadCount: 0
}
}
]
response: {
venues: [
{
id: "5374fa22498e33ddadb073b3"
name: "venue 1"
},
{
id: "5374fa22498e33ddadb073b4"
name: "venue 2"
}
],
neighborhoods: [ ],
confident: true
}
}
The GSON documentation website recommends using GSON's parse API to parse the response as a JSONArray and then read each array item into an appropriate Object or data type (Example here). As such, I originally switched to the following implementation:
JsonParser parser = new JsonParser();
try {
JSONObject json = new JSONObject(response);
JSONArray venues = json.getJSONObject("response").getJSONArray("venues");
int arraylengh = venues.length();
for(int i=0; i < arraylengh; i++){
Log.d(TAG, "The current element is: " + venues.get(i).toString());
}
}
catch(JSONException e){
}
The code above gave me a JSONArray with all the "venues". The next problem was that I do not know how to parse/convert the "venues" JSONArray into a ArrayList (for my custom Venue object).
Solution: As outlined on JohnUopini answer I was able to successfully parse the JSON by using the following implementation:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
List<Venue> venues = Arrays.asList(myResponse.getVenues());
With the above code I was able to successfully parse the "meta" as well as the "response" JSON properties into my custom objects.
For reference, below is my Response class (NOTE: The properties were defined as public for testing purposes. A final implementation should have these declared as private and use setters/getters for encapsulation):
public class Response {
#SerializedName("venues")
public Venue[] venues;
#SerializedName("confident")
public boolean confident;
Response(){}
}
Note/Feedback: After implementing the accepted answer's recommendation, a couple of times I encountered the following (or similar) exception message during my debugging process:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
The reason I was getting the above exception was because the "type" on some of the children inside the "venues" JSON did not match with the "type" I defined such objects in my custom Venue class. Make sure the type in your custom Classes has a 1-to-1 correspondence with the JSON (i.e. [ ] is a array property, { } is an Object property, etc).
This is correct because the object you are trying to access is not an array, you should do something like this:
JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
Or you can create an object containing 3 classes for the 3 objects and then parse everything through GSON.
Json response should look like :
"{\"syncrequest\":{\"user\":{\"#xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\",\"active\":\"true\",\"basedataset\":\"false\"},\"syncversion\":\"89\",\"syncdata\":[{\"operation\":\"INSERT
OR
REPLACE\",\"table\":\"WSInformation\",\"rows\":[{\"WS_ID\":\"71\",\"WS_ParentOwn\":null,\"WS_Notes\":\"Notes\\"for\\"VistaStore
Fleet\\"save\",\"CC_ID\":\"1\",\"Record_Instance\":\"1\",\"Record_LastModified\":\"2013-11-26T07:51:35.203\"}]}]}}"
Response coming from server with a string format. When i convert the above string in json format using
JsonObject jObject =new JsonObject(string);
its getting error like unterminated character in string.
Can any body help me out for above problem.
Thanks In advance
Edited :
The response coming from server is in the form of input stream .
So, I used to convert the inputstream to string using the function :
IOUtils.readStream(instream);
Then the response string should like :
string response =
"{\"syncrequest\":{\"user\":{\"#xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\",\"active\":\"true\",\"basedataset\":\"false\"},\"syncversion\":\"89\",\"syncdata\":[{\"operation\":\"INSERT
OR
REPLACE\",\"table\":\"WSInformation\",\"rows\":[{\"WS_ID\":\"71\",\"WS_ParentOwn\":null,\"WS_Notes\":\"Notes\\"for\\"VistaStore
Fleet\\"save\",\"CC_ID\":\"1\",\"Record_Instance\":\"1\",\"Record_LastModified\":\"2013-11-26T07:51:35.203\"}]}]}}"
By using the below function to form the json object,I removing the double quotes.
res = response.substring(1, response.length() - 1);
and removing double quotes with in the string using the below function.
res = response.replace("\\"", "\"");
Don't use JsonObject in conversion.
JSONObject jObject = new JSONObject(response);
JSONArray jArray = jObject.getJSONArray("syncrequest");
import this org.json.JSONObject;
not com.google.gson.JsonObject;
I think it's not a valid JSON-object.
How I can convert any object (eg array) in json and get in the format string?
For example:
public String jsonEncode(Object obj) {
return jsonString;
}
You can use GSON library to convert any serializable objects into json String.
Here is the Tutorial how-do-convert-java-object-to-from-json-format-gson-api/
If you're asking how to do generic object serialization into json format in java, use reflection. Luckily, lots of the work is done for you, for example this or this.
If you want to go the other way, or specificially you want more control over your serialization, you can still use reflection with annotations. See the jackson mapper
For example:
Hashtable<String, String> capitales = new Hashtable<String, String>();
capitales.put("España", "Madrid");
capitales.put("Francia", "Paris");
String miStringArray[] = { "String1", "String2" };
And I do:
SONObject obj = new JSONObject();
try {
obj.put("name", "Jack Hack");
obj.put("score", miStringArray);
obj.put("otracosa", capitales );
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(obj);
Show:
{"score":"[Ljava.lang.String;#413587d0","otracosa":"{Portugal=Lisboa, Francia=Paris, Argentina=Buenos Aires, España=Madrid}","name":"Jack Hack"}
I'm trying to use GSON to parse some very simple JSON. Here's my code:
Gson gson = new Gson();
InputStreamReader reader = new InputStreamReader(getJsonData(url));
String key = gson.fromJson(reader, String.class);
Here's the JSON returned from the url:
{
"access_token": "abcdefgh"
}
I'm getting this exception:
E/AndroidRuntime(19447): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
Any ideas? I'm new to GSON.
The JSON structure is an object with one element named "access_token" -- it's not just a simple string. It could be deserialized to a matching Java data structure, such as a Map, as follows.
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Map<String, String> map = new Gson().fromJson(jsonInput, new TypeToken<Map<String, String>>() {}.getType());
String key = map.get("access_token");
System.out.println(key);
}
}
Another common approach is to use a more specific Java data structure that matches the JSON. For example:
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Response response = new Gson().fromJson(jsonInput, Response.class);
System.out.println(response.key);
}
}
class Response
{
#SerializedName("access_token")
String key;
}
Another "low level" possibility using the Gson JsonParser:
package stackoverflow.questions.q11571412;
import com.google.gson.*;
public class GsonFooWithParser
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
JsonElement je = new JsonParser().parse(jsonInput);
String value = je.getAsJsonObject().get("access_token").getAsString();
System.out.println(value);
}
}
If one day you'll write a custom deserializer, JsonElement will be your best friend.
This is normal parsing exception occurred when Pojo key data type is different from json response
This is due to data type mismatch in Pojo class and actually data which comes in the Network api Response
Eg
data class ProcessResponse(
val outputParameters: String,
val pId: Int
)
got the same error due to api gives response as
{
"pId": 1",
"outputParameters": {
"": ""
}
}
Here POJO is outputParameters is String but as per api response its json