how can I get response value (json) to String via Java - java

I have the json format like following
{
"items": [
{
"id": 0,
"name": "name1"
},
{
"id": 1,
"name": "name2"
}
]
}
I want to filter name from it , Array name = [name1, name2]
#GET (Web service)
#Produces(MediaType.APPLICATION_JSON)
public Response getItem() {
ClientConfig config = new ClientConfig();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(getUserName(),getUserPassword());
config.register(feature);
Client client = ClientBuilder.newClient(config);
WebTarget service = client.target(getURI() + "/Item");
Response response = service.request().header("Content-Type", "application/json").get();
return response;
}
I have already tried here
http://gotoanswer.com/?q=How+to+Parse+the+this+JSON+Response+in+JAVA
then success.
But how can I do to dynamicaly get json format from Response to string
so that I can input to String jsonString.

When you are parsing your json, the 'items' is an array in your json. So if you try to get the 'items' you will need to type cast it to JSONArray. And iterating on this JSONArray you can get the values of the array using the attributes defined like 'name' and 'id'.
Can you try like this?
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray items = (JSONArray) jsonObject.get("items");
for (int 1 = 0; i < items.length(); i++)
{
System.out.println( items.get(i).get("name");
}
Hope it will help you.

Related

Why does my Spring project return A JSONArray text must start with '[' at 1?

I'm new to Spring Boot and json so forgive me if a silly question. I'm trying to read in my json file, convert it to a JSONObject, then
convert this to a JSONArray. I've commented out the two lines which do
this as I tried going from reading the file to the Array instead. My
JSON file starts with a [ so I'm unsure why I get this error.
Exception in thread "main" org.json.JSONException: A JSONArray text
must start with '[' at 1 [character 2 line 1]
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/req.json");
List<PIECase> allCases = new ArrayList<PIECase>();
InputStream rawJson = inputStream;
//JSONObject jsonObject = new JSONObject(rawJson);
//JSONArray jsonArray = jsonObject.getJSONArray("PIECases");
JSONArray jsonArray = new JSONArray(rawJson.toString());
for(int i =0; i < jsonArray.length(); i++) {
//the JSON data we get back from array as a json object
JSONObject jsonPIECases = jsonArray.getJSONObject(i);
// more code
}
req.json
[
{
"PIECases": {
"PIECases": [
{
"Case_ID": "1",
"SortCode": "123456",
"AccountNumber": "12345678",
"Amount": "50",
"DateOfPayment": "2019-07-29"
},
{
"Case_ID": "2",
"SortCode": "123456",
"AccountNumber": "12345678",
"Amount": "50",
"DateOfPayment": "2019-07-29"
}
]
}
}
]
rawJson.toString() does not return the json content but just the result of default Object#toString() method of the InputStream, use;
JsonReader jsonReader = Json.createReader(inputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();
from JsonArray

How to access JSON data with multiple array objects : android

I am stuck in getting the data from the JSON file with multiple data sets.
{
"status": "ok",
"count": 3,
"count_total": 661,
"pages": 133,
"posts": [
{
"id": 20038,
"type": "post",
"slug": "xperia-launcher-download",
"url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
"status": "publish",
"title": "Download Xperia Launcher app for Android (Latest Version)"
},
{
"id": 94,
"type": "post",
"slug": "top-free-calling-apps-of-2014-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android November 2014"
},
{
"id": 98,
"type": "post",
"slug": "top-free-calling-apps-of-2016-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android December 2016"
}
]
}
I need to access the title, url and status from the above JSON file.
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
} catch (JSONException e) {
Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
I am getting a JSONException with the above code.
What should I do to access the title,status and url from the JSON File?
You have to fetch your JSONArray which is inside a JSONObject , so create a JSONObject and fetch your array with index "posts"
1.) result is a JSONObject so create a JSONObject
2.) Fetch your JSONArray with index value as "posts"
3.) Now simply traverse array objects by fetching it through index
JSONObject jObj = new JSONObject(result);
JSONArray jArray = jObj.getJSONArray("posts");
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
Note : i don't know weather it is a sample response with shorter version though your json object should ends with } not with , .
[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download
Xperia Launcher app for Android (Latest Version)",
// ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like => ...st Version)"},
{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best
Free Calling Apps for Android November 2014", ]
Improvements :
you can use optString to avoid null or non-string value if there is no mapping key
This has two variations
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
fishData.status = json_data.optString("status","N/A");
// will return "N/A" if no key found
or To get empty string if no key found then simply use
fishData.status = json_data.optString("status");
// will return "" if no key found where "" is an empty string
You can validate your JSON here.
If entire JSON getJsonObject() is not working, then you should parse JSON objects & array in multiple arrays then use them.

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Getting the values from a JSON string in Java using GSON

I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);

parse json rest response in java

I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}

Categories