Parsing String to JsonObject - java

I'm getting a list of values from a query with MongoDB I'm using MongoRepository and the method findAll, the answer I'm getting is a List of Informacion
public Informacion[] getAll() {
List<Informacion> info = repoInfo.findAll();
String json =new Gson().toJson(info);
Informacion[] array = info.toArray(new Informacion[info.size()]);
return array;
}
the list I'm getting I parse into JSON, but I can't convert it into a JSONObject to work properly with all the values inside, this is the JSON string :
Informacion{ preferencias=[Preferencias(nombrePref=Rock),
Preferencias(nombrePref=Tatuajes)], numTelefono='0984623854',
usuario='#Bryan810', redes=[RedesSociales(nombreRedSocial=Twitter)],
fechaRecarga=Fri Dec 21 11:30:59 COT 2018}
working with this as a String is really hard because values like Preferencias has many values but if I can transform the String to JSONObject I think I can't handle it better.
So my question is how can I transform "JSON" String to a JSONObject?

Related

Using Java, how to add some node to an existing json at the start of array?

The below code inserts the "myvalue" field to the existing JSON but after the "id" key-value pair, I want to insert a value in this JSON but before the "id" field.
String originalJson="{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}";
String modifiedJson= JsonPath.parse(originalJson)
.add("$.checkouts[0].line_items","myValue")
.jsonString();
The current output of the above code is :
{"checkouts":[{"line_items":[{"id":"343f1f49d0ba7752b5ba84e0184384f4"},"myValue"]}]}
But I want an output like this :
{"checkouts":[{"line_items":["myValue",{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}
You can do this:
String originalJson="{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
DocumentContext json = JsonPath.parse(originalJson);
JSONArray array = json.read("$.checkouts[0].line_items");
array.add(0, "myValue");
String modifiedJson= json
.set("$.checkouts[0].line_items",array)
.jsonString();

how to extract json body as string using java

I have a JSON response and i am extracting the body using getbody() command and storing the responses in list. because i am passing multiple JSON at a time so each response i am storing in list as string value. How can i extract that JSON using JAVA?
response = request.post(route.payment());
body = response.getBody();
listofBody.add(body.asString());
above code is where i get the response and store that into list. before converting to JSON i can do response.jsonPath().getList("company"); to get the values
To extract the element from JSON string you can use Google's Gson Library
Example:
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass().getSimpleName());
}

Java - Retrieving nested JSON array key values

I've got a JSON response that looks like this:
USER:[{
"id":"145454",
"name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true,
"caregiverName":"Jones"
}]
I'm trying to create a java method so I can access the key value pairs of the nested JSONArray. For example I don't want the entire JSON array I just want to retrieve the doctor name from the patientInfo JSON array. Any ideas how I would do this in Java I'm completely stuck here.
This is sudo code but I imagine it would be something like:
String doctorInfo() {
JSONObject obj = new JSONObject(user)
JSONArray arr = obj.getJSONArray("patientInfo")
String doctor = arr.getValue("doctor")
}
And I'd like to be able to access it on the front end by doing
doctorInfo().doctor
Code samples are greatly appreciated.
The code will be like this:
String doctorInfo(String jsonString) {
JSONObject obj = new JSONObject(jsonString)
JSONArray arr = obj.getJSONArray("patientInfo")
JSONObject patientJSONObject = arr.getJSONObject(0);
String doctor = patientJSONObject.getString("doctor");
return doctor;
}
The above code sample assumes you are passing the below string as the parameter.
{ "id":"145454", "name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true, "caregiverName":"Jones" }

how to parse given data into a java object

I want to parse below given data in to some java object, but I am not able to parse. String is as follows -
{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}
I have tried parsing this into HashMap and HashMap
but this is returning malformed JSON exception, and that is making sense, because of too many double quotes objects are ending abruptly. I want to parse this as follows-
{
"objectsTree":"{"Address":[],"Customer":["Address"]}",
"objectsSequence":"["Customer","Address"]"
}
here you can see that objectsTree is one object against one string and objectSequence is another. to be specific object tree is supposed to be a treemap , object sequence is supposed to be a ArrayList.
Any Idea how should I proceed.
code update-
package org.syncoms.backofficesuite.controller;
import java.util.HashMap;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
//String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
String json ="{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}";
Gson jsonParser = new Gson();
#SuppressWarnings("unchecked")
HashMap<String,Object> jo = (HashMap<String,Object>) jsonParser.fromJson(json, HashMap.class);
System.out.println(jo);
//Assert.assertNotNull(jo);
//Assert.assertTrue(jo.get("Success").getAsString());
}
}
the error which I am getting -
Exception in thread "main" com.google.gson.JsonParseException: Failed parsing JSON source: java.io.StringReader#201644c9 to Json
at com.google.gson.JsonParser.parse(JsonParser.java:59)
at com.google.gson.Gson.fromJson(Gson.java:443)
at com.google.gson.Gson.fromJson(Gson.java:396)
at com.google.gson.Gson.fromJson(Gson.java:372)
at org.syncoms.backofficesuite.controller.Test.main(Test.java:16)
Caused by: com.google.gson.ParseException: Encountered " <IDENTIFIER_SANS_EXPONENT> "Address "" at line 1, column 19.
Was expecting one of:
"}" ...
"," ...
The main issue here is that the input is simply not a valid JSON String, and no JSON parser is going to accept it. the doulbe qoutes have to be escaped.
a Valid JSON String is as follows:
String jsonInput = "{\"objectsTree\":\"{\\\"Address\\\":[],\\\"Customer\\\":[\\\"Address\\\"]}\",\"objectsSequence\":\"[\\\"Customer\\\",\\\"Address\\\"]\"}";
and this can be parsed using, for instance, Jackson:
ObjectMapper om = new ObjectMapper();
TypeFactory tf = om.getTypeFactory();
JavaType mapType = tf.constructMapType(HashMap.class, String.class, String.class);
Map<String, String> map = (Map<String, String>)om.readValue(jsonInput, mapType);
System.out.println(map);
Printout is:
{objectsSequence=["Customer","Address"], objectsTree={"Address":[],"Customer":["Address"]}}
There are multiple ways you could do that.
Firstly, if your data has always the same format you can simply create some methods which will create your TreeMap and ArrayList as required. You can do everything you want with String.replace(), StringTokenizer, matcher pattern. You can split your data into tokens and based on your needs place them in your required data structure. I find this way quite efficient and once you get to know better how to parse data and extract what you need, you can use this in many other examples.
If your data is formatted in JSON then there might be even easier ways of parsing it.You can decode it as Java object quite easy.
JSON string is not well formed one. Try as below
{
"objectsTree":{"Address":[],"Customer":["Address"]},
"objectsSequence":["Customer","Address"]
}
JSON key is always string &
JSON values can be:
•A number (integer or floating point)
•A string (in double quotes)
•A Boolean (true or false)
•An array (in square brackets)
•An object (in curly braces)
•null.
See the below code with well formed string and its output
String a = "{\r\n" +
"\"objectsTree\":{\"Address\":[],\"Customer\":[\"Address\"]},\r\n" +
"\"objectsSequence\":[\"Customer\",\"Address\"]\r\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Object> jo = (HashMap<String,Object>) mapper.readValue(a, HashMap.class);
System.out.println("result: "+ jo);
result: {objectsTree={Address=[], Customer=[Address]}, objectsSequence=[Customer, Address]}
with your json string
String json ="{\"objectsTree\":\"{\"Address\":[],\"Customer\":[\"Address\"]}\",\"objectsSequence\":\"[\"Customer\",\"Address\"]\"}";
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Object> jo = (HashMap<String,Object>) mapper.readValue(json, HashMap.class);
System.out.println("result: "+ jo);
error :
Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting comma to separate OBJECT entries
at [Source: java.io.StringReader#77d2b01b; line: 1, column: 20]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
In your json string, for key objectsTree, the value is started with \" and its matching \" is closed before string Address. This is causing the parse error.
"{\"Address
The other two answers also saying that your json string is in invalid format.
I also added the supported json values for your reference.
If you change to correct format, any json parser will work,

Decoding JSON in Java

im really new to java through Eclipse android, and im trying to decode this line of JSON
{"FullName":"bobby Bloggs"}
But when i try to put it into an array through
JSONObject jsonObject = new JSONObject(httpData);
JSONObject feedObject = jsonObject.getJSONObject("FullName");
I hit an exception of
org.json.JSONException: Value bobby Bloggs at FullName of type java.lang.String cannot be converted to JSONObject
Thanks
You are trying to read a String, since {} within the JSON means it is an object. Everything between "" means it's a string. true/false a boolean (getBoolean) and numbers are an Integer (getInteger). Since you want the String you need to use.
String FullName = JSONObject.getString("FullName");
You are trying to get JSONObject out of JSON Object i.e jsonObject.getJSONObject("FullName"); and again assigning to JSONObject.
As suggested by Emanuel use getString to get the data of "FullName" as and assign to a String.
JSONObject jsonObj = new JSONObject(httpData);
String FullName = jsonObj.getString("FullName");
will work.

Categories