how to do json parser in android using json structure - json

I have json structure like as shown in image. How should I use jsonparser for this?

Use like this
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
String response = object.getString("response");
} catch (JSONException e) {
e.printStackTrace();
}

Create Model class like your JSON
and use GSON library to parse your json into model.

Related

Why am I getting Json Malformed Exception?

I'm trying to make a program using json to save user registers to file, but when I try to read my json I get the error "JSON malformed". This is my code to write in json:
Gson gsonObject = new Gson();
FileWriter writerFile;
try {
writerFile = new FileWriter("users.json", true);
writerFile.write(gsonObject.toJson(writerUser));
writerFile.close();
} catch (IOException e) {
e.printStackTrace();
}
I use arrays to be easy modify the values (only take the json back to array and make my modify) but i can't reader this json file after writer, this is my reader code:
Gson gson = new Gson();
List<User> userList;
try {
BufferedReader readerUserList = new BufferedReader(new FileReader("users.json"));
userList = Arrays.asList(gson.fromJson(readerUserList, User[].class));
for (User user : userList) {
System.out.println(user.toString());
}
And after that i get "json malformed" error, where is my error?
If help you guys, inside my json file is my arrays like that:
[{"name":"james","idCode":1}][{"name":"kyle","idCode":2}][{"name":"test","idCode":3}]
I've never used Gson... but your json file has format problems, it is supposed to look like this:
[{"name":"james","idCode":1},{"name":"kyle","idCode":2},{"name":"test","idCode":3}]
The problem is not when you try to read, but when you write it.

Java index json data to solr

I try to index json data to solr.
SolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
SolrInputDocument document = new SolrInputDocument();
String stringToParse = "{\"id\": \"101\",\"name\": \"Baia Otel\",\"services\":[{\"room_id\":\"1234\",\"service_name\":\"Shuttle\"},{\"room_id\":\"1235\",\"service_name\":\"Accommodation\"}]}";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(stringToParse);
document.addField("info", json.toJSONString());
} catch (ParseException e) {
e.printStackTrace();
}
On document.addField method if I use json.toJSONString() it indexes json data as string, and when I just use jsonObject without casting it to JSONString;
document.addField("info",json)
it does not index this field.
How can I index json to solr so that it will be indexed nested?
You can find examples of indexing JSON with Solrj for schemaless Solr in this blog.

How to return array of JSON when AngularJs component call it by URL

I going to use AngularJs component "ng-grid" to show the list of person on that data-grid. In "main.js" that component should read the data from an URL like this
$http.get('http://localhost:7001/UserPortal/test/json/JsonResualt.jsf').success(function (largeLoad)
and my problem is how to define it !
Actually I wrote a method to fetch data and convert it to the JSONArray like this
public String toJson(){
String query = "select * from t_person";
JSONObject jsObj = new JSONObject();
JSONArray prsJsonArray = new JSONArray();
try {
ArrayList<PersonBean> persons = some code to fetch data
for (PersonBean personBean : persons) {
JSONObject prsJsObj = new JSONObject();
prsJsObj.putOpt(String.valueOf(persons.indexOf(personBean)), personBean);
prsJsonArray.put(prsJsObj);
}
jsObj.put("prsJsonArray", prsJsonArray);
getResponse().setContentType("application/json");
getResponse().getWriter().write(jsObj.toString());
} catch (Throwable e) {
e.printStackTrace();
}
}
When I debug it, in 'prsJsonArray' I have array of JSON data and I could wite it on response object.
My question is, How could I call this method directly from URL ? Or could I do some way else to handle this issue ?!
I use J2EE and EJB and my web page is JSF
Thanks in advance .
You got something completly wrong. You use a JSF page as a webservice, which is terrible. If you wan't to create a webservice to retrieve JSON objects, you should create a restful service with something like Spring or JAX-RS.
For Example with JAX-RS:
#Path("userportal/json/metallica")
public class JSONService {
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
//Or retrieve data from DB by calling a DAO for example
return track;
}
}

How does play.libs.Json.fromJson handled a List<T> in Java?

I'd like to use the Json library that comes with the play 2.1 framework.
But I'm stuck with deserializing a json object back into a java List.
With gson, you can write s.th. like
Type type = new TypeToken<List<XYZ>>(){}.getType();
List<XYZ> xyzList = gson.fromJson(jsonXyz, type);
Is there a way to do the same with play.libs.Json.fromJson ?
Any help appreciated.
Edit (17.12.2013):
I did the following to work around the problem. I guess there is a better way, but I didn't found it.
List<MyObject> response = new ArrayList<MyObject>();
Promise<WS.Response> result = WS.url(Configuration.getRestPrefix() + "myObjects").get();
WS.Response res = result.get();
JsonNode json = res.asJson();
if (json != null) {
for (JsonNode jsonNode : json) {
if (jsonNode.isArray()) {
for (JsonNode jsonNodeInner : jsonNode) {
MyObject mobj = Json.fromJson(jsonNodeInner, MyObject.class);
response.add(bst);
}
} else {
MyObject mobj = Json.fromJson(jsonNode, MyObject.class);
response.add(bst);
}
}
}
return response;
The Json library for Play Java is really just a thin wrapper over the Jackson JSON library (http://jackson.codehaus.org/). The Jackson way to deserialize a list of custom objects is mentioned here.
For your case, once you parse the json from the response body, you would do something like this, assuming MyObject is a plain POJO:
JsonNode json = res.asJson();
try{
List<MyObject> objects = new ObjectMapper().readValue(json, new TypeReference<List<MyObject>>(){});
}catch(Exception e){
//handle exception
}
I'm assuming you were asking about Play Java based on your edit, Play Scala's JSON library is also based on Jackson but has more features and syntactic sugar to accommodate functional programming patterns.
You can use the following code:
List<YourClass> returnedRoles = new ObjectMapper().readValue(jsonString
,TypeFactory.defaultInstance().constructCollectionType(List.class,
YourClass.class));

Retrieving JSON Object Literal from HttpServletRequest

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved