Error while converting JSON to Java Object - java

I want to convert JSON to a java object. I created a class and I wrote code like this.I am getting exception o/p:Unexpected character (c) at position 0
I'm getting the JSON data from the client. but when I try to convert JSON to java I'm getting an error
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource("my url");
String name = "adn";
String password = "12";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString
.getBytes());
// System.out.println("Base64 encoded auth string: " +
// authStringEnc);
ClientResponse response = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
String output = response.getEntity(String.class);
output = output.substring(13, output.length() - 1);
System.out.println(output);
JSONParser parse = new JSONParser();
counts count=new counts();
JSONObject jobj = (JSONObject)parse.parse(output);
JSONArray jsonarr_1 = (JSONArray) jobj.get("Counts");
// System.out.println(jsonarr_1.get(1));
JSONArray array = new JSONArray();
//Get data for Results array
for(int i=0;i<jsonarr_1.length();i++)
{
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
System.out.println("Elements under results array");
System.out.println("\nPlace id: " +jsonobj_1.get("college_name"));
System.out.println("Types: " +jsonobj_1.get("college_epass_id"));
}
I am getting the JSON data from client. I want to convert the JSON to java object. I created pojo(counts) class also. The json data is like this:
o/p:college_name":"GPT n,
Kakda","college_epass_id":128},{"college_name":"GT,
am","college_epass_id":2946}
error:
Unexpected character (c) at position 0.

Use of Jackson
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
Your classes will be some like
public class CollegeList{
#JsonProperty("counts")
public List<College> counts;
}
public class College{
#JsonProperty("college_name") public String college_name;
#JsonProperty("college_epass_id") public int college_epass_id;
}
You can convert the json into respective object by
CollegeList colleges = mapper.readValue(jsonString, CollegeList .class);
Sharing Reference Link for more details.

I think your issue is that you are truncating the response on this line...
output = output.substring(13, output.length() - 1);
This will make the JSON string invalid
Perhaps you should consider removing this line of code or creating a separate variable to store the substring.

Related

How to retreive data from Json using java

hi guys i have json response like this
Response response = service.execute(requestSendToNS);
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
System.out.println("Response Body : " + response.getBody());
and here the result :
Response Body : [{"status":"success","message":"update success","id":"1404","internalid":2604},{"status":"failed","message":"bad location is already used in another location","id":1405}]
my question is how to getting value "id" from my json response ?
i have try use this code :
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
i also have use this
List responseObject = objectMapper.readValue(response.getBody(),List);
but i cannot mapping from json Array to object
but i cannot retreive value from id
Your response body is an array.
[{...},{...}]
That's why you can't get id
String data = jsonResponse.getString("id");
Please have a look JsonReader to read json as JsonArray
https://docs.oracle.com/javaee/7/api/javax/json/JsonReader.html#readObject--
JsonReader jsonReader = Json.createReader(new StringReader(response.getBody()));
JsonArray array = jsonReader.readArray();
JsonObject obj = array.getJsonObject(0);
String data = obj.getString("id");
First, you have to create a class that has the exact same structure as the JSON response, and then you can use ObjectMapper from jackson library to write the JSON to class and read the values from it.

How to convert a ClientResponse to a java array or java object?

I'm using jersey to call different Rest Api and I've searched for a solution to convert the response to java array or list this is the output :
[{"name":"TEST","number":22,"successNumber":11,"runnedNumber":20,"percentage":0.5},{"name":"SCENARIO","number":29,"successNumber":10,"runnedNumber":12,"percentage":0.34},{"name":"TESTCASE","number":11,"successNumber":6,"runnedNumber":9,"percentage":0.55}]
I tried resp.getEntity(String.class) but this returned a string and i need
to convert it to List or Array or any other data structure so i can manipulate the data because i'm trying to make charts.
this the method that i used to make the API Call:
public ClientResponse callApi(String url) throws IOException {
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
System.out.println("Base64 encoded auth string: " + authStringEnc);
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
System.out.println("response: "+output);
return resp;
}
It can be achieved by following snippet:
String response = response.getEntity().toString();
JSONArray jsonArray = (JSONArray) new JSONParser().parse(response);
String[] stringArray = jsonArray.toArray(new String[jsonArray.size()]);
I solved it i used the objectMapper from jackson
String json = "json string";
ObjectMapper objectMapper = new ObjectMapper();
List<YourClass> listClass = objectMapper.readValue(json, new TypeReference<List<YourClass>>(){});

how to convert json data to java object and how to separate json data fields

I am consuming data from url and stored in "output" string. How to convert that into java object and separate fields ?
Here is my code :
Client client = Client.create();
WebResource webResource = client
.resource(url);
String name = "xxx";
String password = "xxx";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString
.getBytes());
//System.out.println("Base64 encoded auth string: " + authStringEnc);
ClientResponse response = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
you can use gson for this. import gson to your project.
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
//..
//you can get the output here
//String output = response.getEntity(String.class);
Type listType = new TypeToken<FooObject>(){}.getType();
FooObject fooObject =new Gson().fromJson(output, listType);

how to access json array element in java

i am getting json array in the output.i want to access the specific key elments from the response .how can i ..?
ResponseEntity <String> respone;
try {
response =
restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String response=response.getBody();
JSONObject res = new JSONObject();
res.put("result", response);
System.out.println(res);
int len=res.size();
System.out.println(len);
JSONParser parser=new JSONParser();
Object obj = parser.parse(response);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(0)); }
this is respponse format i m getting in output.i want to access the bid from the response.how can i?
[
{
"bName": "abc",
"bId": "n86nbnhbnghgy76"
}
]
Decode your string using JSONArray(String json) constructor:
String response = response.getBody();
JSONArray res = new JSONArray(response);
String bId = res.getJSONObject(0).get("bId");
System.out.println(bid);
EDIT
Try following:
String response=response.getBody();
JSONObject res = new JSONObject();
System.out.println(res);
int len=res.size();
System.out.println(len);
JSONParser parser=new JSONParser();
Object obj = parser.parse(response);
JSONArray array = (JSONArray)obj;
res=(JSONObject)array.get(0);
System.out.println(res.get("bId"));
Output :
n86nbnhbnghgy76
This one is based on your code and with Simple Json Library.

Java String to JSON conversion

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :
URL url = new URL("SOME URL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
JSONObject jObject = new JSONObject(output);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
MY string contain
{"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}
this is the string which i want in json but it shows me Exception in thread "main"
java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:83)
at org.json.JSONObject.<init>(JSONObject.java:310)
at Main.main(Main.java:37)
The name is present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.
JSONObject jObject = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
Note: This example uses the org.json.JSONObject class and not org.json.simple.JSONObject.
As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.
Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.
Sample from the link provided:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-
StringBuilder buffer = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
buffer.append(output);
}
output = buffer.toString(); // now you have the output
conn.disconnect();
Converting the String to JsonNode using ObjectMapper object :
ObjectMapper mapper = new ObjectMapper();
// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)
// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)
// For Json String
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);
Instead of JSONObject , you can use ObjectMapper to convert java object to json string
ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

Categories

Resources