Tag Archives: json

The solution of calling$. Ajax successfully but the success method does not respond

Today, when I was working, I encountered a problem. I used $. Ajax to transfer data to the background, which can operate correctly in the background, but success did not respond, and error responded. After checking the document, I realized that after jQuery version 1.4, all the returned JSON formats must meet the requirements json.org Success can only be called back correctly in the format of, otherwise jQuery will think that it returns an error Here is an example:

JSONObject j = new JSONObject();
j.put("msg","SUCCESS");
PrintWriter out = response.getWriter();
out.write(j.toString());

This is correct. JQuery calls back success

String j = "123";
PrintWriter out = response.getWriter();
out.write(j);

This is wrong, jQuery will think it is wrong

 

How to quickly build JavaBean objects through JSON (IntelliJ idea — > gsonformat tutorial)

When docking with a third party, it’s very common for us to return JSON with many parameter fields, so it must take a lot of time for us to manually create JavaBeans. Bloggers have found many tools on the Internet that can automatically generate JavaBeans through JSON. Here’s a brief introduction to the plug-in gsonformat in IntelliJ idea.

1. What is gson format

As plug-in to convert JSON data format to JavaBean object.

2. Shortcut key: Ctrl + Alt + s, or settings — & gt; plugs — & gt; enter gsonformat install plugins

After the installation is completed, restart IntelliJ idea. First, you need a new class file, and then press Alt + insert to select gsonformat, or Alt + s to pop up the box and enter the string data in JSON format.

Solution to syntaxerror: invalid syntax in PIP install XXX

Solution to syntaxerror: invalid syntax in PIP install XXX

Statement: 1. PIP install requests are taken as an example; 2. Windows system;
first of all, check whether you have run PIP in the python environment. If so, please open the start menu, enter CMD, find the command prompt and open it.
Enter PIP install requests in CMD, If “not an internal or external command, nor a runnable program or batch file” appears, the specific solutions are as follows:
1. Find the folder where Python is located, find the scripts file, and use Ctrl + C to copy the file path. Take an individual as an example: C: 2 2. Return to the desktop, right-click “my computer” and click “properties”
3. In the pop-up page, select “advanced system settings – variable environment – path – Edit – add the file path copied in step 1 and click OK
4. Restart the computer

After restarting the computer, open CMD again, and then enter the command PIP install requests. If
appears, the installation is successful and the problem is solved.

[jQuery] jQuery operates on JSON strings or JSON objects

preface

Most of the time, you need to convert a JSON string to a JSON object, and then process it in a loop, or convert a JSON object to a JSON string as a parameter and pass it to the relevant interface. Next, we will introduce several conversion methods

Assume that the JSON string is

Var jsonstr = ‘[{“Id”: 1, “title”: “Zhang San”, “sex”: “male”}, {“Id”: 2, “title”: “Li Si”, “sex”: “male”}]’;

Assume that the JSON object is

Var jsonobj = [
{
“Id”: 1,
“title”: “Zhang San”,
“sex”: “male”
},
{
“Id”: 2,
“title”: “Li Si”,
“sex”: “male”
}
]

1、 Convert JSON string to JSON array object

1、eval()

var jsonObj = eval('(' + jsonStr + ')');

2、JSON.parse()

var jsonObj = JSON.parse(jsonStr);

Prev

var jsonObj = JSON.parse(jsonStr);

2、 Convert JSON object to JSON string

JSON.stringify ()

var jsonStr = JSON.stringify(jsonObj);

3、 Loop JSON object

for (var i = 0; i < jsonObj.length; i++) {

    var name= jsonObj[i].Title;

}

 

Notes on @ pathvariable annotation in springcloud openfeign

SpringCloud-Feign-@PathVariable
Feign pathvariable annotation was empty on param 0.
when using feign, if the parameter contains

@If the parameter is in the form of pathvariable, the corresponding parameter should be marked with value =, otherwise the IllegalStateException exception will be thrown

as

@GetMapping(value = "/payment/consumer/hystrix/ok/get/{id}")
    public String payment_ok(@PathVariable Integer id)

The above code will report feign pathvariable annotation was empty on param 0

    @GetMapping(value = "/payment/consumer/hystrix/ok/get/{id}")
    public String payment_ok(@PathVariable(value="id") Integer id)

So you can go through

Python json.dumps () json.dump The difference between ()

Dumps is to convert dict to STR format, loads is to convert STR to dict format. Dump and load are similar functions, but they are combined with file operation.

Code example:

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}


dic_c = json.loads(str_b)
print(type(dic_c),dic_c) #<class 'dict'> {'name': 'wang', 'age': 29}

Then we will see the difference between dump and dumps. See the code:

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}

#c = json.dump(dic_a)
# TypeError: dump() missing 1 required positional argument: 'fp'

c = json.dump(dic_a)

Dump needs a parameter similar to a file pointer (not a real pointer, it can be called a file like object), which can be combined with file operation, that is, you can convert dict into STR and then store it in a file; dumps directly gives STR, that is, you can convert dictionary into str.

See the code for an example (pay attention to some small details of file operation)

import json

dic_a = {'name': 'wang', 'age': 29}
str_b = json.dumps(dic_a)
print(type(str_b),str_b) #<class 'str'> {"name": "wang", "age": 29}

#c = json.dump(dic_a)
# TypeError: dump() missing 1 required positional argument: 'fp'

c = json.dump(dic_a,open('str_b.txt','w'))

Note: dump is rarely used in practice.  

Reproduced in: https://my.oschina.net/u/3486061/blog/3065779

JSON data format net.sf.json .JSONException: A JSONObject text must begin with ‘{‘ at character 1 of Error:(f…

The substring (3) the use of the http://www.w3school.com.cn/jsref/jsref_substring.asp

Possibility 1: if sb is the data to be converted, let’s say sb is a String

 


The char
The STR [] = sb. ToString (). ToCharArray ();


for
(
The int
i=
0
; i< str.length; i++){


System.out.println(str[i]);


}

After can get into an array of form, check the array before any Spaces, such as if useful
sb.toString().trim().substring(
1
); Cut off


The String json = sb. ToString (). The trim (). The substring (
1
);


The // String json = "{\" success \ ": true, \" MSG \ ": \ \" successful "} ";


System.out.println(json);


System.out.println(json.length());


The JSONObject JSONObject = JSONObject. FromObject (json. The trim ());


System.out.println(jsonobject);



The

"Result" : [{}] ------ left less {

Possibility 2: No initialization, no initBmob () is likely to report this wrong Unregistered

Possibility 3: There is an extra space before the data in the database

 

Reproduced in: https://www.cnblogs.com/wth21-1314/p/7381575.html

Spring MVC 406 status code / could not find acceptable representation

 
Jackson-core-asl-1.9.12.jar Jackson-mapper-asl-1.9.12.jar
The test is not for this error and does not have to rely on the two JARs.
The following configuration returns data normally
 
pom.xml
 

        <!-- Jackson JSON Processor -->

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

 
 
For springMvc. In the XML
 
 

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>text/xml;charset=utf-8</value>
                        <value>text/plain;</value>
                        <value>text/json;charset=utf-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

 
 
 
 
 
In the Controller
 

  @RequestMapping(value = "checkLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkLogin(String name, String password, int role) {

        return loginService.checkLogin(name, password, role);
    }

 
 
 
——————————————————————————-
The ResultDTO object is missing some of the GET methods, causing an error in formatting the JSON object.
Remove the above two JARs and test with the GET method of the returned object, reporting 406 error code.
The debug code in ServletInvocableHandlerMethod. Catch exceptions in the class “Could not find acceptable representation.” ”
After adding the get method, the test returns the JSON character of the object normally
 
 

public class ResultDto {

    private boolean succeed;
    private Object data;

    public ResultDto(boolean succeed) {
        this.succeed = succeed;
    }

    public ResultDto(boolean succeed, Object data) {
        this.succeed = succeed;
        this.data = data;
    }

/*
    public boolean isSucceed() {
        return succeed;
    }

    public Object getData() {
        return data;
    }
*/

    public void setSucceed(boolean succeed) {
        this.succeed = succeed;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

 
 

 

JS error: unexpected token u in JSON at position 0

At first glance, this error is confusing, but it is simply due to json.parse parsing of undefined.

JSON.parse is used somewhere, but the argument passed in is not a qualified JSON string.
Parse parse parse parse parse parse parse parse parse parse
Parse before you judge
 


Come from:
https://www.cnblogs.com/yangxunwu1992/p/8964780.html