'How do I receive a JSONObject from post on spring boot rest controller (from org.json)
I want my RESTcontroller to get a JSONObject from a post request but when I send this through Postman:
{
"collection":"StudentDB",
"index":{
"joinDate":"2022-12-12"
}
}
It seems to be working, but the problem is that embedded JSONObjects seem to get cast into a LinkedHashmap and not be JSONObjects, so when I run this code:
@PostMapping
@RequestMapping(value="/query",consumes="application/json")
public ResponseEntity query( @RequestBody JSONObject query) {
System.out.println(query.get("index").getClass());
}
Output is:
class java.util.LinkedHashMap
What could be causing this? Is there another way I could do this?
Solution 1:[1]
It looks like the reason why you get java.util.LinkedHashMap value for index key is because under the hood JSONObject uses a Map to store it's key-value pairs.
So each key-value pair(for example, "collection" : "StudentDB") is actually stored in this map that's wrapped in a JSONObject.
And when you wrote "index" : { key-value pairs here }, you essentially told JSONObject that you want to create another Map(for key-value pairs that will be inside of { }) that will be serving as a value for index key.
As for why LinkedHashMap is used here, the reason for that is because JSONObject needs to preserve the ordering of its elements, so LinkedHashMap does just that.
The solution to your problem depends on what you're exactly trying to achieve here. The logic of the program seems to be okay, so hopefully you'll figure out what to do about it based on what I've written here.
Solution 2:[2]
You have a nested/local method BirdDied, that can't have access modifiers. It's accessible only from the method body of Update anyway. So this compiles:
void Update ()
{
void BirdDied()
{
GameOverText.SetActive (true);
gameOver = true;
}
}
But since you don't use it in your code, i doubt that it's what you want.
Solution 3:[3]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird2D : MonoBehaviour
{
public float upForce = 200f;
private bool isDead = false;
private Rigidbody2D rb2d;
private Animator anim;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (isDead == false)
{
if (Input.GetMouseButtonDown(0))
{
rb2d.velocity = Vector2.zero;
rb2d.AddForce(new Vector2(0, upForce));
anim.SetTrigger("Flap");
}
}
}
void OnCollisionEnter2D()
{
isDead = true;
anim.SetTrigger("Die");
GameControl2D.Instance.BirdDied();
}
}
This is the Bird2D.cs file i already remove public from birdDied method but the error is same
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tim Schmelter |
| Solution 3 | Tahrim |
