May i know how to get JSON object from an json array??
JSON:
[
{
"id": 1,
"user": {
"id": 20710,
"username": "abc",
"first_name": "",
"last_name": "",
},
"action": {
"name": "xxx",
"date": 19/01/01,
},
},
{
"id": 2,
"user": {
"username": "xyx",
"first_name": "xxx",
"last_name": "yyy",
},
"action": {
"name": "xxx",
"date": 19/05/01,
},
},]
I want to get username of these users in a list, but i cant get the value when i get this json from api as JSONArray.
My code:
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("Create Response", response.toString());
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = response;
try {
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
JSONObject c=response.getJSONObject(1);
String id = c.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
feeds_List.add(map);
}
}
I cannot use
JSONObject object=JsonArray.getJSONObject("user");
here,
it only accept int for getJSONObject("user"); if it is JSONArray
You can use like this also.Suppose response String is userInfo
ArrayList<String> usernames = new ArrayList<String>();
JSONArray userList = new JSONArray(userInfo);
for (int j = 0; j < userList.length(); j++) {
JSONObject userObject = new JSONObject(userList.getString(j));
String user = userObject.getString("user");
JSONObject usernameInfo = new JSONObject(user);
usernames.add(usernameInfo.getString("username"));
}
Try this, if not working please mention me in comment.
Related
This is my method for POST test
public void createParagraph3() {
RestAssured.baseURI = paragraphsURL;
Map<String, Object> map = new HashMap<String, Object>();
map.put("featurePackage", Arrays.asList(new HashMap<String, String>() {{
put("name", "Test");
put("inputText", "test test");
}}));
map.put("features", Arrays.asList(new HashMap<String, Object>() {{
put("featureType", "Feature");
put("inUse", "true");
put("name", "test xyxy");
}}));
map.put("type", Arrays.asList(new HashMap<String, String>() {{
put("key", "int");
put("name", "Introduction");
}}));
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.body(map).toString();
Response response = request.post();
int statusCode = response.getStatusCode();
System.out.println("Response body: " + response.body().asString());
System.out.println("Status code received: " + statusCode);
}
Below I have my request on basis I'm creating my test
{
"featurePackage": {
"features": [
{
"featureType": "string",
"id": 0,
"inUse": true,
"name": "string"
}
],
"id": 0,
"name": "string",
"objectCount": 0
},
"features": [
{
"featureType": "string",
"id": 0,
"inUse": true,
"name": "string"
}
],
"id": 0,
"inputText": "string",
"objectCount": 0,
"outputHtmlText": "string",
"sourceFileName": "string",
"type": {
"key": "string",
"name": "string"
}
}
What I am doing wrong? I still received 400 response "Cannot deserialize instance". Can someone help? I have incomplete request in my method?
EDIT 1:
The root cause is that map.toString() is not a valid JSON string.
There are two ways for you to solve this problem:
use JSONObject instead of map, see this
convert map to JSON object, see this
PS: A demo about map.toString()
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
System.out.println(map.toString());
// get: {apple=1, banana=2} is NOT a valid JSON String
// but, {"apple":1,"banana":2} is a valid JSON String
EDIT 2:
Since the owner of question added some comments, I have to add the following answer.
Pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
Java code:
// your comment
Map<String, Object> titles = new HashMap<>();
titles.put("titles", Arrays.asList(new HashMap<String, Object>() {
{
put("id", "876");
put("title", "test");
}
}));
System.out.println(titles);
// my new answer
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(titles);
System.out.println(json);
This is the problem that I'm trying to resolve. I have a list of map that I want to convert into JSON array in Groovy.
The list is:
List<Map<String, String>> studentList = [{id=1,name=John,email=john#google.com},{id=2,name=Peter,email=peter#google.com},{id=3,name=James,email=james#google.com}]
Desired JSON output is:
{
students: [{
"id" = "1",
"name" = "John",
"contact": {
"email": "john#google.com"
}
}, {
"id" = "2",
"name" = "Peter",
"contact": {
"email": "peter#google.com"
}
}, {
"id" = "3",
"name" = "James",
"contact": {
"email": "james#google.com"
}
}
]
}
My code only generates 1 student. Can anyone help me please?
def builder = new JsonBuilder()
for (Map student: studentList) {
builder.students {
id student.id
name student.name
contact {
email student.email
}
}
}
println builder.toPrettyString()
Appreciate your time and advice. Thank you.
Pass a list to the builder
You don't need to iterate through the list, you can pass a list to the builder,
using JsonBuilder's implicit call() method.
def builder = new JsonBuilder()
builder {
students builder( studentList )
}
public Object call( List list )
A list of elements as arguments to the JSON builder creates a root JSON array
See the JsonBuilder Groovydoc page for details of the various call()
methods.
Example code
In this example I've fixed up your map, and introduced a small Student class, to
simplify the code.
import groovy.json.JsonBuilder
class Student { int id; String name; String email }
studentList = [
new Student( id:1, name:'John', email:'john#google.com' ),
new Student( id:2, name:'Peter', email:'peter#google.com' ),
new Student( id:3, name:'James', email:'james#google.com' )
]
def builder = new JsonBuilder()
builder {
students builder( studentList )
}
println builder.toPrettyString()
Resulting JSON
{
"students": [
{
"id": 1,
"email": "john#google.com",
"name": "John"
},
{
"id": 2,
"email": "peter#google.com",
"name": "Peter"
},
{
"id": 3,
"email": "james#google.com",
"name": "James"
}
]
}
I have solved it with ff code.
def students = []
def builder = new JsonBuilder()
for (Map student: studentList) {
builder {
id student.id
name student.name
contact {
email student.email
}
}
students.add(builder.toString())
}
def jsonSlurper = new JsonSlurper()
def items = jsonSlurper.parseText(students.toString())
def json = new JsonBuilder()
json "students": items
println json.toPrettyString()
This is the response I am getting from server. All the properties are String and int expect data. It is a list of objects. When serializing the response it shows error. Please explain what is wrong with my code. I am from javascript background. Serialization in flutter is different from javascript.
class ResponseModel {
String image;
int row;
int column;
int position;
List<Data> data;
ResponseModel({this.image, this.row, this.column, this.position});
factory ResponseModel.fromJson(Map<String, dynamic> parsedJson) {
return ResponseModel(
image: parsedJson['image'],
row: parsedJson['row'],
column: parsedJson['column'],
position: parsedJson['position'],
);
}
}
class Data {
String imageUrl;
Data({this.imageUrl});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
return Data(imageUrl: parsedJson["imageUrl"]);
}
}
[
{
"type": "image",
"row": 1,
"column": 3,
"position":"1",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/6dad06016c6ab319.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/9ad209b0fc3d03e4.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/405e10d01fae5aa5.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 2,
"position":"3",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/f186565389063212.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/3eda035d946b0ebf.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 1,
"position":"2",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/1187/636/image/4436d492e2563998.jpg?q=90"
}
]
}
]
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
final finalResponse = ResponseModel.fromJson(parsedJson);
print(finalResponse);
setState(() {
data = parsedJson;
});
}
Error image
You can use this tool and select dart Language
Its because the response is a JSON array. Which means json.decode(response.body) returns a List<dynamic> and hence the variable parsedJson is List.
You're trying to pass this List as a parameter to the ResponseModel.fromJson(Map<String, dynamic>) method which accepts a Map as the parameter.
In simple words, you're trying to pass a List where a Map is expected.
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
List<ResponseModel> responseList = <ResponseModel>[];
parsedJson.foreach((element) {
responseList.add(ResponseModel.fromJson(element));
})
///Response list will have your data
print(responseList);
}
Your code should be something like this
I was not able to get JsonObject while I try to covert JsonObject to JsonArray
JSON DATA:
{
"in”: [
{
"Action": "In",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "OUT",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "In",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
}
],
"click": [
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Sep 27, 2019"
},
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
}
]
}
and I use the below code to get those objects using the "Get" method
how to get "click" objects alone,
i tried below code
URL url = new URL("https://localdummy.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
and get those details in "inline"
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println(inline);
sc.close();
}
Then got those object into array
JSONObject jobj = new JSONObject (inline);
JSONArray jsonarr_1 = (JSONArray) jobj.get("in"); //its working
//JSONArray jsonarr_1 = (JSONArray) jobj.get("click"); <- <- <- <-//its not working . i need to use this ((((its issues))))
please help me to get jobj in to jsonarr_1 for get "click"
Thanks in advance
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Demo{
public static void main(String[] args) {
String resp = "{\"in\":[{\"Action\":\"In\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"OUT\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"In\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"}],\"click\":[{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Sep27,2019\"},{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"}]}";
JSONObject jsonObject = JSONObject.parseObject(resp);
JSONArray click = jsonObject.getJSONArray("click");
System.out.println(click);
}
}
you will get what you want:
[{"Action":"Click","InDate":"Sep 27, 2019","namespace":"Zdesk"},{"Action":"Click","InDate":"Nov 4, 2019","namespace":"Zdesk"},{"Action":"Click","InDate":"Nov 4, 2019","namespace":"Zdesk"}]
hope to help you
I need to create multiple Json arrays at a single instance. I have 38 rows. For 38 rows first I need to create 38 empty JSON arrays. Then in each JSON array i need to add first column of row as first object in all the arrays. Second column as 2nd object etc. Is there a way to specify the position to add the objects in each array?
[
[
{
"fileName": "123"
},
{
"id": "100"
},
{
"product": ""
}
],
[
{
"fileName": "123"
},
{
"id": "100"
},
{
"product": ""
}
]...38
]
package emp;
import javax.lang.model.element.PackageElement;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Temp
{
public static void main(String[] args) throws JSONException {
JSONArray jsonArray = new JSONArray();
jsonArray.put(createJsonArray("name 1", "id 1", "product 1"));
jsonArray.put(createJsonArray("name 2", "id 2", "product 2"));
jsonArray.put(createJsonArray("name 3", "id 3", "product 3"));
System.out.println(jsonArray.toString());
}
public static JSONArray createJsonArray(String name, String id, String product) throws JSONException
{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("fileName", "123");
jsonArray.put(jsonObject);
jsonObject.put("id", "123");
jsonArray.put(jsonObject);
jsonObject.put("product", "product");
jsonArray.put(jsonObject);
return jsonArray;
}
}