search
HomeBackend DevelopmentPHP Tutorialphp生成的json传给android gson无法解析

1.php json_encode 生成的json传输给android 用gson无法解析

2.$arr = array('token'=>'111','id'=>'1','contacts'=>array('name'=>'11','tel'=>'188'));
就是这种数组中包含数组 转换成json 发送给 android android用gson无法解析。

PHP多维关联数组用json_encode生成json串 android用gson不识别
用索引数组生成的则可以

回复内容:

1.php json_encode 生成的json传输给android 用gson无法解析

2.$arr = array('token'=>'111','id'=>'1','contacts'=>array('name'=>'11','tel'=>'188'));
就是这种数组中包含数组 转换成json 发送给 android android用gson无法解析。

PHP多维关联数组用json_encode生成json串 android用gson不识别
用索引数组生成的则可以

推荐在Android使用GsonFormat集成到AS中,可以很方便的生产符合的javaBean,如果你Android端解析代码没写错得话就不会有什么问题的。
下面是使用该工具对应你的json生成的javaBean:

<code>public class ceshi {

    /**
     *token : 111
     *id : 1
     *contacts : {"name":"11","tel":"188"}
     */

    private String token;
    private String id;
    /**
     *name : 11
     *tel : 188
     */

    private ContactsBean contacts;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public ContactsBean getContacts() {
        return contacts;
    }

    public void setContacts(ContactsBean contacts) {
        this.contacts = contacts;
    }

    public static class ContactsBean {
        private String name;
        private String tel;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getTel() {
            return tel;
        }

        public void setTel(String tel) {
            this.tel = tel;
        }
    }
}</code>

要不你把转换出来的json和你用来接收json的实体类发一下?

不同语言,不同版本解析 json 的库可能实现上有所不同
php 是内置,所以很容易调用,有些语言要使用第三方的类库
所以干脆问 android 拿接收到的字符串是怎么样的,然后你在用php json_decode,看看能不能解析

gson不能解析php的json字符串,主要看,Android客户端接收到的json字符串是否完整,如果完整,在使用gson的时候,转换成java对象,虽然gson支持泛型,但是至少你要提供json字符串对应的javaBean实例,否则转换一定失败。

<code>$arr = array('token'=>'111','id'=>'1','contacts'=>array('name'=>'11','tel'=>'188'));
</code>

在java中应该对应一个class,该类必须有String token,int id,Object contacts,而contacts对应两一个类,该类必须有String name,String tel属性。

Test.java

<code>package test.joyven.com;
public class Test {
    private int id;
    private String token;
    private Contacts contacts;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }
    public Contacts getContacts() {
        return contacts;
    }
    public void setContacts(Contacts contacts) {
        this.contacts = contacts;
    }
    
}
</code>

Contacts.java

<code>package test.joyven.com;

public class Contacts {
    private String name;
    private String tel;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    
}
</code>

把json串打印出来,看看json结构,我估计是你java bean的格式不对。

<code>Model[] models = new Gson().fromJson(JsonStr, Model[].class);
</code>
<code>public class Model{
    public int id;
    public String token;
    public Contacts[] contacts;
}

public class Contacts {
    public String name;
    public String tel;
}


</code>

最简单的做法,是用Map去解析你的json,遇到对象就进行强制转换,虽然不优雅,但通用。针对那些不太清楚自己的Bean写法的人比较好用。上面的回复都是bean的对应写法。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor