How to Split a JSON string to two JSON objects in Java - java

I have a JSON object as follows:
{
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"user":{
"pk":17,
"username":"user1",
"email":"user1#gmail.com",
"first_name":"",
"last_name":""
}
}
I am trying to get two JSON object from it; token and user. I have tried two different ways but both are failing:
//response.body().string() is the above json object
JSONArray jsonArray = new JSONArray(response.body().string());
jsonObjectRoot = new JSONObject(response.body().string());
Could any one please let me know how I could split this to two JSON objects?

You can split it this way:
// source object
JSONObject sourceObject = new JSONObject(sourceJson);
String tokenKey = "token";
// create new object for token
JSONObject tokenObject = new JSONObject();
// transplant token to new object
tokenObject.append(tokenKey, sourceObject.remove(tokenKey));
// if append method does not exist use put
// tokenObject.put(tokenKey, sourceObject.remove(tokenKey));
System.out.println("Token object => " + tokenObject);
System.out.println("User object => " + sourceObject);
Above code prints:
Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}
User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}}

You can parse a json string with
var obj = JSON.parse(jsonString);
You can filter sub parts of a json object by simply addressing them
var token = obj.token;
var user = obj.user;

The safer / cleaner way to do it is to create a POJO and deserialize your JSON into it using Jackson. Your pojo:
public class MyObject {
String token;
User user;
static class User {
int pk;
String username;
String email;
String first_name;
String last_name;
}
}
Then, when you want to deserialize:
import com.fasterxml.jackson.databind.ObjectMapper;
and
ObjectMapper mapper = new ObjectMapper();
MyObject myObject = mapper.readValue(jsonString, MyObject.class);
String token = myObject.token;
User user = myObject.user;
...

I recently faced the same situation, I used the below code which worked for me:
JSONObject jo1 = new JSONObject(output);
JSONObject tokenObject = new JSONObject();
tokenObject.put("token", jo1.get("token"));
JSONObject userObject = new JSONObject();
userObject.put("user", jo1.get("user"));
Here I am creating a new empty JSONObject and then put the retrieved object from the original object in the newly created JSONObject.
You can also verify the output by just sysout:
System.out.println("token:" + tokenObject.get("token"));
System.out.println("user:" + userObject.get("user"));
Output in my case :
token::eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
user:{"last_name":"","pk":17,"first_name":"","email":"user1#gmail.com","username":"user1"}

Yep. It is a JSON string.
Using like this
JSONParser jparse=new JSONParser();
JSONObject jObj=(JSONObject)jParse.parse(jsonString);
jObj will contain json Object now.

Related

JSON Input for POST request to call REST API

How do i convert a model Person to match the input?
Person p = new Person(name, age, amountInBank);
(name in String, age in int and amountInBank in double)
I want my JSON Input to be as follow:
{
"ID": "H123",
"list" : [
{
"name" : "ally",
"age": 18,
"amountInBank": 200.55
}
]
}
Currently my code to call REST API is:
JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");
//put in list input in JSON -> HELP NEEDED
Resource resource = client.resource(URL HERE);
resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);
ClientResponse cliResponse = resource.post(jsonInput);
Tried many ways but couldn't achieve the expected input for list in JSON format. Please help
Method 1:
ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);
Method 2:
JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);
Method 3:
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);
Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:
ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert
Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.
If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.
Try the code below
val listJsonArry = JsonArray()
var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")
listJsonArry.add(jsonObject)
PostData
var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)
First you have to create JSONObject and put ID, H123.
Then you have to create Another JSONObject wich will accept a person details.
pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(); // first json object
jsonObject.put("ID", "H123"); put ids.
JSONArray jsonArray = new JSONArray(); // prepear json array
Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data
// JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class.
JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
jsonObject1.put("name", person.getName());
jsonObject1.put("age", person.getAge());
jsonObject1.put("amountInBank", person.getAmountInBank());
jsonArray.put(jsonObject1); // pass json object to json array
jsonObject.put("list", jsonArray); // and pass json array to json object
System.out.println();
try (FileWriter file = new FileWriter("person.json")) {
file.write(jsonObject.toString(5));
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
above code will produce output
{
"ID": "H123",
"list": [{
"name": "Ally",
"amountInBank": 200.55,
"age": 18
}]
}
if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.

Stuck Parsing nested JSON Array

I'm stuck parsing a nested JSON Array. This should be fairly simple but I can't seem to get it to work.
I have a JSON Array like below:
{"currentPage":0,
"totalPages":1,
"totalSize":1,
"first":true,
"last":true,
"list"[{"date":"2018-11-07T09:34:25.042+0000",
"lastUpdated":"2018-11-07T09:34:25.266+0000",
"id"130674,
"active":true,
"address":null,
"storeMobileNumbers":
[{"id":130676,"mobile":"+201008005090","version":0
}]
}]
}
I'm trying to get the address from the list first, then get the values from storeMobileNumbers.
I have a POJO class for the list, and now I have created a POJO class for the StoreMobileNumbers.
This is what I have right now:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Type collectionType = new TypeToken<List<MyStore>>(){}.getType();
Type collection2 = new TypeToken<List<StoreMobileNumber>>({}.getType();
JSONObject obj = new JSONObject(json);
if (obj.has("list")) {
String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType);
JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.toJSONObject(obj1);
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);
}
My StoreMobileNumbersClass:
public class StoreMobileNumber{
public Long id;
public String mobile;
}
So far, my efforts have been unsuccessful. I'm getting the following error:
org.json.JSONException: No value for storeMobileNumbers
Can someone help me see what I'm missing here?
Change to following -
String myList = obj.get("list").toString();
list1 = gson.fromJson(myList, collectionType); // delete this not required
JSONArray obj1 = new JSONArray(list1);
JSONObject numbersObject = obj1.getJsonObject(0); // change this to get first object from the JsonArray
String mobileList =
numbersObject.get("storeMobileNumbers").toString();
mobileNumbers = gson.fromJson(mobileList, collection2);

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Convert JsonObject to String

{
"data":
{
"map":
{
"allowNestedValues": true,
"create": "2012-12-11 15:16:13",
"title": "test201212110004",
"transitions": []
}
},
"msg": "success",
"code": "0"
}
Above is a JsonObject, the data is a JsonObject.
How to convert it to a String like "msg":"success" as you know, i can't directly add a double quotes outside data's value.
There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:
JSONObject json = new JSONObject();
json.toString();
You can use:
JSONObject jsonObject = new JSONObject();
jsonObject.toString();
And if you want to get a specific value, you can use:
jsonObject.getString("msg");
or Integer value
jsonObject.getInt("codeNum");
For long Integers
jsonObject.getLong("longNum");
you can use
JsonObject.getString("msg");
You can try Gson convertor, to get the exact conversion like json.stringify
val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)
JsonObject seems to be JSON-P API. If this is true, I would use JsonWritter to write JsonValue into StringWriter:
JsonObjectBuilder pokemonBuilder = Json.createObjectBuilder();
pokemonBuilder.add("name", "Pikachu");
pokemonBuilder.add("type", "electric");
pokemonBuilder.add("cp", 827);
pokemonBuilder.add("evolve", true);
JsonObject pokemon = pokemonBuilder.build();
StringWriter sw = new StringWriter(128);
try (JsonWriter jw = Json.createWriter(sw)) {
jw.write(pokemon);
}
String pokemonStr = sw.toString();
Add a double quotes outside the brackets and replace double quotes inside the {} with \"
So: "{\"data\":{..... }"
Use This :
JSONObject json = new JSONObject();
JSONObject.valueToString(json.toString());
JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;
just use ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
//here more config opts...
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
String carAsString = objectMapper.writeValueAsString(car);
JSONObject data = (JSONObject) data.get("map");
//for example
String jsonString = data.toJSONString();
Example of Model
public class Person {
private String name;
private String age;
// setter and getter
// toString method
}
Example of Service method
public String getPerson() {
JSONObject returnObj = new JSONObject();
Person person = new Person();
person.setAge("24");
person.setName("Fazal");
returnObj.put("age", person.getAge());
returnObj.put("name", person.getName());
return returnObj.toString();
}
Json in java dependency needed
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>{New_Version}</version>
</dependency>
You will get this type of JSON result
This should get all the values from the above JsonObject
System.out.println(jsonObj.get("msg"));
System.out.println(jsonObj.get("code"));
JsonObject obj= jsonObj.get("data").getAsJsonObject().get("map").getAsJsonObject();
System.out.println(obj.get("allowNestedValues"));
System.out.println(obj.get("create"));
System.out.println(obj.get("title"));
System.out.println(obj.get("transitions"));
You can use reliable library GSON
private static final Type DATA_TYPE_JSON =
new TypeToken<JSONObject>() {}.getType();
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());
var data= {"data": {"map":{"allowNestedValues": true,"create": "2012-12-11 15:16:13","title": "test201212110004","transitions": []}},"msg": "success","code": "0"}
o/p:
Object {data: Object, msg: "success", code: "0"}
Use JSON.stringify to convert entire data into string like below
var stringData = JSON.stringify(data);
o/p:
"{"data":{"map":{"allowNestedValues":true,"create":"2012-12-11 15:16:13","title":"test201212110004","transitions":[]}},"msg":"success","code":"0"}"
Use JSON.parse to convert entire string object into JSON Object like below
var orgdata = JSON.parse(stringData);
o/p:
Object {data: Object, msg: "success", code: "0"}
I think you need this :
Suppose you have Sample JSON like this :
{"ParamOne":"InnerParamOne":"InnerParamOneValue","InnerParamTwo":"InnerParamTwoValue","InnerParamThree":"InnerParamThreeValue","InnerParamFour":"InnerParamFourValue","InnerParamFive":"InnerParamFiveValue"}}
Converted to String :
String response = {\"ParamOne\":{\"InnerParamOne\":\"InnerParamOneValue\",\"InnerParamTwo\":\"InnerParamTwoValue\",\"InnerParamThree\":\"InnerParamThreeValue\",\"InnerParamFour\":\"InnerParamFourValue\",\"InnerParamFive\":\"InnerParamFiveValue\"}} ;
Just replace " by \"

Is JSON same with GSON?

I have tried to run following code
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();
JSONArray data = new JSONArray();
for (Object obj : result) {
JSONArray row = new JSONArray();
User user = (User) obj;
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();
The result from toString function for both jsonResponse are as follows:
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}
I would like to eliminate the " symbol before [ and after ] from the first json response just like the second one (I noticed that the " is added after the array being put to the jsonResponse object). How can I accomplish this ?
Since you first convert your "result" to a String, and then add it to aaData, it will end up quoted, like a String should. If all you'd like to do is to remove the quotes, you could do something like this in line 2:
String json = "##" + gson.toJson(result) + "##";
and this in line 8:
jsonResponse.toString().replace("\"##", "").replace("##\"","");
(of course you need to choose the "quote marker" ## such that it will never appear as actual string content in your data anywhere else)
But the cleaner solution (although probably slower) would likely be to convert your String to an actual JSONObject by changing line 2 to:
JSONObject json = new JSONObject(gson.toJson(result));

Categories

Resources